]> granicus.if.org Git - icinga2/blob - lib/cli/nodesetupcommand.cpp
ApiListener#ApiTimerHandler(): delete all replayed logs
[icinga2] / lib / cli / nodesetupcommand.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://icinga.com/)      *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program is distributed in the hope that it will be useful,            *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "cli/nodesetupcommand.hpp"
21 #include "cli/nodeutility.hpp"
22 #include "cli/featureutility.hpp"
23 #include "cli/apisetuputility.hpp"
24 #include "remote/apilistener.hpp"
25 #include "remote/pkiutility.hpp"
26 #include "base/logger.hpp"
27 #include "base/console.hpp"
28 #include "base/application.hpp"
29 #include "base/tlsutility.hpp"
30 #include "base/scriptglobal.hpp"
31 #include "base/exception.hpp"
32 #include <boost/algorithm/string/join.hpp>
33 #include <boost/algorithm/string/replace.hpp>
34
35 #include <iostream>
36 #include <fstream>
37 #include <vector>
38
39 using namespace icinga;
40 namespace po = boost::program_options;
41
42 REGISTER_CLICOMMAND("node/setup", NodeSetupCommand);
43
44 String NodeSetupCommand::GetDescription() const
45 {
46         return "Sets up an Icinga 2 node.";
47 }
48
49 String NodeSetupCommand::GetShortDescription() const
50 {
51         return "set up node";
52 }
53
54 void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc,
55         boost::program_options::options_description& hiddenDesc) const
56 {
57         visibleDesc.add_options()
58                 ("zone", po::value<std::string>(), "The name of the local zone")
59                 ("endpoint", po::value<std::vector<std::string> >(), "Connect to remote endpoint; syntax: cn[,host,port]")
60                 ("parent_host", po::value<std::string>(), "The name of the parent host for auto-signing the csr; syntax: host[,port]")
61                 ("parent_zone", po::value<std::string>(), "The name of the parent zone")
62                 ("listen", po::value<std::string>(), "Listen on host,port")
63                 ("ticket", po::value<std::string>(), "Generated ticket number for this request (optional)")
64                 ("trustedcert", po::value<std::string>(), "Trusted master certificate file")
65                 ("cn", po::value<std::string>(), "The certificate's common name")
66                 ("accept-config", "Accept config from master")
67                 ("accept-commands", "Accept commands from master")
68                 ("master", "Use setup for a master instance")
69                 ("global_zones", po::value<std::vector<std::string> >(), "The names of the additional global zones to 'global-templates' and 'director-global'.")
70                 ("disable-confd", "Disables the conf.d directory during the setup");
71
72         hiddenDesc.add_options()
73                 ("master_zone", po::value<std::string>(), "DEPRECATED: The name of the master zone")
74                 ("master_host", po::value<std::string>(), "DEPRECATED: The name of the master host for auto-signing the csr; syntax: host[,port]");
75 }
76
77 std::vector<String> NodeSetupCommand::GetArgumentSuggestions(const String& argument, const String& word) const
78 {
79         if (argument == "key" || argument == "cert" || argument == "trustedcert")
80                 return GetBashCompletionSuggestions("file", word);
81         else if (argument == "host")
82                 return GetBashCompletionSuggestions("hostname", word);
83         else if (argument == "port")
84                 return GetBashCompletionSuggestions("service", word);
85         else
86                 return CLICommand::GetArgumentSuggestions(argument, word);
87 }
88
89 ImpersonationLevel NodeSetupCommand::GetImpersonationLevel() const
90 {
91         return ImpersonateRoot;
92 }
93
94 /**
95  * The entry point for the "node setup" CLI command.
96  *
97  * @returns An exit status.
98  */
99 int NodeSetupCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
100 {
101         if (!ap.empty()) {
102                 Log(LogWarning, "cli")
103                         << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
104         }
105
106         if (vm.count("master"))
107                 return SetupMaster(vm, ap);
108         else
109                 return SetupNode(vm, ap);
110 }
111
112 int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
113 {
114         /* Ignore not required parameters */
115         if (vm.count("ticket"))
116                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --ticket");
117
118         if (vm.count("endpoint"))
119                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --endpoint");
120
121         if (vm.count("trustedcert"))
122                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --trustedcert");
123
124         String cn = Utility::GetFQDN();
125
126         if (vm.count("cn"))
127                 cn = vm["cn"].as<std::string>();
128
129         /* Setup command hardcodes this as FQDN */
130         String endpointName = cn;
131
132         /* Allow to specify zone name. */
133         String zoneName = "master";
134
135         if (vm.count("zone"))
136                 zoneName = vm["zone"].as<std::string>();
137
138         /* check whether the user wants to generate a new certificate or not */
139         String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";
140
141         Log(LogInformation, "cli")
142                 << "Checking in existing certificates for common name '" << cn << "'...";
143
144         if (Utility::PathExists(existingPath)) {
145                 Log(LogWarning, "cli")
146                         << "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate.";
147         } else {
148                 Log(LogInformation, "cli")
149                         << "Certificates not yet generated. Running 'api setup' now.";
150
151                 ApiSetupUtility::SetupMasterCertificates(cn);
152         }
153
154         Log(LogInformation, "cli", "Generating master configuration for Icinga 2.");
155         ApiSetupUtility::SetupMasterApiUser();
156
157         if (!FeatureUtility::CheckFeatureEnabled("api")) {
158                 ApiSetupUtility::SetupMasterEnableApi();
159         } else {
160                 Log(LogInformation, "cli")
161                         << "'api' feature already enabled.\n";
162         }
163
164         /* write zones.conf and update with zone + endpoint information */
165         Log(LogInformation, "cli", "Generating zone and object configuration.");
166
167         std::vector<String> globalZones { "global-templates", "director-global" };
168         std::vector<std::string> setupGlobalZones;
169
170         if (vm.count("global_zones"))
171                 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
172
173         for (int i = 0; i < setupGlobalZones.size(); i++) {
174                 if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
175                         Log(LogCritical, "cli")
176                                 << "The global zone '" << setupGlobalZones[i] << "' is already specified.";
177                         return 1;
178                 }
179         }
180
181         globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
182
183         /* Generate master configuration. */
184         NodeUtility::GenerateNodeMasterIcingaConfig(endpointName, zoneName, globalZones);
185
186         /* Update the ApiListener config. */
187         Log(LogInformation, "cli", "Updating the APIListener feature.");
188
189         String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
190         NodeUtility::CreateBackupFile(apipath);
191
192         std::fstream fp;
193         String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
194
195         fp << "/**\n"
196                 << " * The API listener is used for distributed monitoring setups.\n"
197                 << " */\n"
198                 << "object ApiListener \"api\" {\n";
199
200         if (vm.count("listen")) {
201                 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
202
203                 if (tokens.size() > 0)
204                         fp << "  bind_host = \"" << tokens[0] << "\"\n";
205                 if (tokens.size() > 1)
206                         fp << "  bind_port = " << tokens[1] << "\n";
207         }
208
209         fp << "\n";
210
211         if (vm.count("accept-config"))
212                 fp << "  accept_config = true\n";
213         else
214                 fp << "  accept_config = false\n";
215
216         if (vm.count("accept-commands"))
217                 fp << "  accept_commands = true\n";
218         else
219                 fp << "  accept_commands = false\n";
220
221         fp << "\n"
222                 << "  ticket_salt = TicketSalt\n"
223                 << "}\n";
224
225         fp.close();
226
227 #ifdef _WIN32
228         _unlink(apipath.CStr());
229 #endif /* _WIN32 */
230
231         if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
232                 BOOST_THROW_EXCEPTION(posix_error()
233                         << boost::errinfo_api_function("rename")
234                         << boost::errinfo_errno(errno)
235                         << boost::errinfo_file_name(tempApiPath));
236         }
237
238         /* update constants.conf with NodeName = CN + TicketSalt = random value */
239         if (endpointName != Utility::GetFQDN()) {
240                 Log(LogWarning, "cli")
241                         << "CN/Endpoint name '" <<  endpointName << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
242         }
243
244         NodeUtility::UpdateConstant("NodeName", endpointName);
245         NodeUtility::UpdateConstant("ZoneName", zoneName);
246
247         String salt = RandomString(16);
248
249         NodeUtility::UpdateConstant("TicketSalt", salt);
250
251         Log(LogInformation, "cli")
252                 << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
253
254         if (vm.count("disable-confd")) {
255                 /* Disable conf.d inclusion */
256                 if (NodeUtility::UpdateConfiguration("\"conf.d\"", false, true)) {
257                         Log(LogInformation, "cli")
258                                 << "Disabled conf.d inclusion";
259                 } else {
260                         Log(LogWarning, "cli")
261                                 << "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
262                 }
263
264                 /* Include api-users.conf */
265                 String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();
266
267                 if (Utility::PathExists(apiUsersFilePath)) {
268                         NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
269                 } else {
270                         Log(LogWarning, "cli")
271                                 << "Included file doesn't exist " << apiUsersFilePath;
272                 }
273         }
274
275         /* tell the user to reload icinga2 */
276         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
277
278         return 0;
279 }
280
281 int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
282 {
283         /* require at least one endpoint. Ticket is optional. */
284         if (!vm.count("endpoint")) {
285                 Log(LogCritical, "cli", "You need to specify at least one endpoint (--endpoint).");
286                 return 1;
287         }
288
289         if (!vm.count("zone")) {
290                 Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
291                 return 1;
292         }
293
294         /* Deprecation warnings. TODO: Remove in 2.10.0. */
295         if (vm.count("master_zone"))
296                 Log(LogWarning, "cli", "The 'master_zone' parameter has been deprecated. Use 'parent_zone' instead.");
297         if (vm.count("master_host"))
298                 Log(LogWarning, "cli", "The 'master_host' parameter has been deprecated. Use 'parent_host' instead.");
299
300         String ticket;
301
302         if (vm.count("ticket"))
303                 ticket = vm["ticket"].as<std::string>();
304
305         if (ticket.IsEmpty()) {
306                 Log(LogInformation, "cli")
307                         << "Requesting certificate without a ticket.";
308         } else {
309                 Log(LogInformation, "cli")
310                         << "Requesting certificate with ticket '" << ticket << "'.";
311         }
312
313         /* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
314         bool connectToParent = false;
315         String parentHost;
316         String parentPort = "5665";
317         std::shared_ptr<X509> trustedParentCert;
318
319         /* TODO: remove master_host in 2.10.0. */
320         if (!vm.count("master_host") && !vm.count("parent_host")) {
321                 connectToParent = false;
322
323                 Log(LogWarning, "cli")
324                         << "Node to master/satellite connection setup skipped. Please configure your parent node to\n"
325                         << "connect to this node by setting the 'host' attribute for the node Endpoint object.\n";
326         } else {
327                 connectToParent = true;
328
329                 String parentHostInfo;
330
331                 if (vm.count("parent_host"))
332                         parentHostInfo = vm["parent_host"].as<std::string>();
333                 else if (vm.count("master_host")) /* TODO: Remove in 2.10.0. */
334                         parentHostInfo = vm["master_host"].as<std::string>();
335
336                 std::vector<String> tokens = parentHostInfo.Split(",");
337
338                 if (tokens.size() == 1 || tokens.size() == 2)
339                         parentHost = tokens[0];
340
341                 if (tokens.size() == 2)
342                         parentPort = tokens[1];
343
344                 Log(LogInformation, "cli")
345                         << "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";
346
347         }
348
349         /* retrieve CN and pass it (defaults to FQDN) */
350         String cn = Utility::GetFQDN();
351
352         if (vm.count("cn"))
353                 cn = vm["cn"].as<std::string>();
354
355         Log(LogInformation, "cli")
356                 << "Using the following CN (defaults to FQDN): '" << cn << "'.";
357
358         /* pki request a signed certificate from the master */
359         String certsDir = ApiListener::GetCertsDir();
360         Utility::MkDirP(certsDir, 0700);
361
362         String user = Configuration::RunAsUser;
363         String group = Configuration::RunAsGroup;
364
365         if (!Utility::SetFileOwnership(certsDir, user, group)) {
366                 Log(LogWarning, "cli")
367                         << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << certsDir << "'. Verify it yourself!";
368         }
369
370         String key = certsDir + "/" + cn + ".key";
371         String cert = certsDir + "/" + cn + ".crt";
372         String ca = certsDir + "/ca.crt";
373
374         if (Utility::PathExists(key))
375                 NodeUtility::CreateBackupFile(key, true);
376         if (Utility::PathExists(cert))
377                 NodeUtility::CreateBackupFile(cert);
378
379         if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
380                 Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
381                 return 1;
382         }
383
384         /* fix permissions: root -> icinga daemon user */
385         if (!Utility::SetFileOwnership(key, user, group)) {
386                 Log(LogWarning, "cli")
387                         << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!";
388         }
389
390         /* Send a signing request to the parent immediately, or leave it to the user. */
391         if (connectToParent) {
392                 /* In contrast to `node wizard` the user must manually fetch
393                  * the trustedParentCert to prove the trust relationship (fetched with 'pki save-cert').
394                  */
395                 if (!vm.count("trustedcert")) {
396                         Log(LogCritical, "cli")
397                                 << "Please pass the trusted cert retrieved from the parent node (master or satellite)\n"
398                                 << "(Hint: 'icinga2 pki save-cert --host <masterhost> --port <5665> --key local.key --cert local.crt --trustedcert parent.crt').";
399                         return 1;
400                 }
401
402                 trustedParentCert = GetX509Certificate(vm["trustedcert"].as<std::string>());
403
404                 Log(LogInformation, "cli")
405                         << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
406
407                 Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
408
409                 if (PkiUtility::RequestCertificate(parentHost, parentPort, key, cert, ca, trustedParentCert, ticket) > 0) {
410                         Log(LogCritical, "cli")
411                                 << "Failed to fetch signed certificate from parent Icinga node '"
412                                 << parentHost << ", "
413                                 << parentPort << "'. Please try again.";
414                         return 1;
415                 }
416         } else {
417                 /* We cannot retrieve the parent certificate.
418                  * Tell the user to manually copy the ca.crt file
419                  * into DataDir + "/certs"
420                  */
421                 Log(LogWarning, "cli")
422                         << "\nNo connection to the parent node was specified.\n\n"
423                         << "Please copy the public CA certificate from your master/satellite\n"
424                         << "into '" << ca << "' before starting Icinga 2.\n";
425
426                 if (Utility::PathExists(ca)) {
427                         Log(LogInformation, "cli")
428                                 << "\nFound public CA certificate in '" << ca << "'.\n"
429                                 << "Please verify that it is the same as on your master/satellite.\n";
430                 }
431         }
432
433         if (!Utility::SetFileOwnership(ca, user, group)) {
434                 Log(LogWarning, "cli")
435                         << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!";
436         }
437
438         /* fix permissions (again) when updating the signed certificate */
439         if (!Utility::SetFileOwnership(cert, user, group)) {
440                 Log(LogWarning, "cli")
441                         << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!";
442         }
443
444         /* disable the notifications feature */
445         Log(LogInformation, "cli", "Disabling the Notification feature.");
446
447         FeatureUtility::DisableFeatures({ "notification" });
448
449         /* enable the ApiListener config */
450
451         Log(LogInformation, "cli", "Updating the ApiListener feature.");
452
453         FeatureUtility::EnableFeatures({ "api" });
454
455         String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
456         NodeUtility::CreateBackupFile(apipath);
457
458         std::fstream fp;
459         String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
460
461         fp << "/**\n"
462                 << " * The API listener is used for distributed monitoring setups.\n"
463                 << " */\n"
464                 << "object ApiListener \"api\" {\n";
465
466         if (vm.count("listen")) {
467                 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
468
469                 if (tokens.size() > 0)
470                         fp << "  bind_host = \"" << tokens[0] << "\"\n";
471                 if (tokens.size() > 1)
472                         fp << "  bind_port = " << tokens[1] << "\n";
473         }
474
475         fp << "\n";
476
477         if (vm.count("accept-config"))
478                 fp << "  accept_config = true\n";
479         else
480                 fp << "  accept_config = false\n";
481
482         if (vm.count("accept-commands"))
483                 fp << "  accept_commands = true\n";
484         else
485                 fp << "  accept_commands = false\n";
486
487         fp << "\n"
488                 << "}\n";
489
490         fp.close();
491
492 #ifdef _WIN32
493         _unlink(apipath.CStr());
494 #endif /* _WIN32 */
495
496         if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
497                 BOOST_THROW_EXCEPTION(posix_error()
498                         << boost::errinfo_api_function("rename")
499                         << boost::errinfo_errno(errno)
500                         << boost::errinfo_file_name(tempApiPath));
501         }
502
503
504         /* Generate zones configuration. */
505         Log(LogInformation, "cli", "Generating zone and object configuration.");
506
507         /* Setup command hardcodes this as FQDN */
508         String endpointName = cn;
509
510         /* Allow to specify zone name. */
511         String zoneName = vm["zone"].as<std::string>();
512
513         /* Allow to specify the parent zone name. */
514         String parentZoneName = "master";
515
516         if (vm.count("parent_zone"))
517                 parentZoneName = vm["parent_zone"].as<std::string>();
518
519         std::vector<String> globalZones { "global-templates", "director-global" };
520         std::vector<std::string> setupGlobalZones;
521
522         if (vm.count("global_zones"))
523                 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
524
525         for (int i = 0; i < setupGlobalZones.size(); i++) {
526                 if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
527                         Log(LogCritical, "cli")
528                                 << "The global zone '" << setupGlobalZones[i] << "' is already specified.";
529                         return 1;
530                 }
531         }
532
533         globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
534
535         /* Generate node configuration. */
536         NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);
537
538         /* update constants.conf with NodeName = CN */
539         if (endpointName != Utility::GetFQDN()) {
540                 Log(LogWarning, "cli")
541                         << "CN/Endpoint name '" << endpointName << "' does not match the default FQDN '"
542                         << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
543         }
544
545         NodeUtility::UpdateConstant("NodeName", endpointName);
546         NodeUtility::UpdateConstant("ZoneName", zoneName);
547
548         if (!ticket.IsEmpty()) {
549                 String ticketPath = ApiListener::GetCertsDir() + "/ticket";
550
551                 String tempTicketPath = Utility::CreateTempFile(ticketPath + ".XXXXXX", 0600, fp);
552
553                 if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
554                         Log(LogWarning, "cli")
555                                 << "Cannot set ownership for user '" << user
556                                 << "' group '" << group
557                                 << "' on file '" << tempTicketPath << "'. Verify it yourself!";
558                 }
559
560                 fp << ticket;
561
562                 fp.close();
563
564 #ifdef _WIN32
565                 _unlink(ticketPath.CStr());
566 #endif /* _WIN32 */
567
568                 if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
569                         BOOST_THROW_EXCEPTION(posix_error()
570                                 << boost::errinfo_api_function("rename")
571                                 << boost::errinfo_errno(errno)
572                                 << boost::errinfo_file_name(tempTicketPath));
573                 }
574         }
575
576         /* If no parent connection was made, the user must supply the ca.crt before restarting Icinga 2.*/
577         if (!connectToParent) {
578                 Log(LogWarning, "cli")
579                         << "No connection to the parent node was specified.\n\n"
580                         << "Please copy the public CA certificate from your master/satellite\n"
581                         << "into '" << ca << "' before starting Icinga 2.\n";
582         } else {
583                 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
584         }
585
586         if (vm.count("disable-confd")) {
587                 /* Disable conf.d inclusion */
588                 NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
589         }
590
591         /* tell the user to reload icinga2 */
592         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
593
594         return 0;
595 }