summaryrefslogtreecommitdiffstats
path: root/lib/cli/nodesetupcommand.cpp
blob: 2a685b503b4b6e249a022c7e1075230d6651fafe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "cli/nodesetupcommand.hpp"
#include "cli/nodeutility.hpp"
#include "cli/featureutility.hpp"
#include "cli/apisetuputility.hpp"
#include "remote/apilistener.hpp"
#include "remote/pkiutility.hpp"
#include "base/atomic-file.hpp"
#include "base/logger.hpp"
#include "base/console.hpp"
#include "base/application.hpp"
#include "base/tlsutility.hpp"
#include "base/scriptglobal.hpp"
#include "base/exception.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>

#include <iostream>
#include <fstream>
#include <vector>

using namespace icinga;
namespace po = boost::program_options;

REGISTER_CLICOMMAND("node/setup", NodeSetupCommand);

String NodeSetupCommand::GetDescription() const
{
	return "Sets up an Icinga 2 node.";
}

String NodeSetupCommand::GetShortDescription() const
{
	return "set up node";
}

void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc,
	boost::program_options::options_description& hiddenDesc) const
{
	visibleDesc.add_options()
		("zone", po::value<std::string>(), "The name of the local zone")
		("endpoint", po::value<std::vector<std::string> >(), "Connect to remote endpoint; syntax: cn[,host,port]")
		("parent_host", po::value<std::string>(), "The name of the parent host for auto-signing the csr; syntax: host[,port]")
		("parent_zone", po::value<std::string>(), "The name of the parent zone")
		("listen", po::value<std::string>(), "Listen on host,port")
		("ticket", po::value<std::string>(), "Generated ticket number for this request (optional)")
		("trustedcert", po::value<std::string>(), "Trusted parent certificate file as connection verification (received via 'pki save-cert')")
		("cn", po::value<std::string>(), "The certificate's common name")
		("accept-config", "Accept config from parent node")
		("accept-commands", "Accept commands from parent node")
		("master", "Use setup for a master instance")
		("global_zones", po::value<std::vector<std::string> >(), "The names of the additional global zones to 'global-templates' and 'director-global'.")
		("disable-confd", "Disables the conf.d directory during the setup");

	hiddenDesc.add_options()
		("master_zone", po::value<std::string>(), "DEPRECATED: The name of the master zone")
		("master_host", po::value<std::string>(), "DEPRECATED: The name of the master host for auto-signing the csr; syntax: host[,port]");
}

std::vector<String> NodeSetupCommand::GetArgumentSuggestions(const String& argument, const String& word) const
{
	if (argument == "key" || argument == "cert" || argument == "trustedcert")
		return GetBashCompletionSuggestions("file", word);
	else if (argument == "host")
		return GetBashCompletionSuggestions("hostname", word);
	else if (argument == "port")
		return GetBashCompletionSuggestions("service", word);
	else
		return CLICommand::GetArgumentSuggestions(argument, word);
}

ImpersonationLevel NodeSetupCommand::GetImpersonationLevel() const
{
	return ImpersonateIcinga;
}

/**
 * The entry point for the "node setup" CLI command.
 *
 * @returns An exit status.
 */
int NodeSetupCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
{
	if (!ap.empty()) {
		Log(LogWarning, "cli")
			<< "Ignoring parameters: " << boost::algorithm::join(ap, " ");
	}

	if (vm.count("master"))
		return SetupMaster(vm, ap);
	else
		return SetupNode(vm, ap);
}

int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
{
	/* Ignore not required parameters */
	if (vm.count("ticket"))
		Log(LogWarning, "cli", "Master for Node setup: Ignoring --ticket");

	if (vm.count("endpoint"))
		Log(LogWarning, "cli", "Master for Node setup: Ignoring --endpoint");

	if (vm.count("trustedcert"))
		Log(LogWarning, "cli", "Master for Node setup: Ignoring --trustedcert");

	String cn = Utility::GetFQDN();

	if (vm.count("cn"))
		cn = vm["cn"].as<std::string>();

	/* Setup command hardcodes this as FQDN */
	String endpointName = cn;

	/* Allow to specify zone name. */
	String zoneName = "master";

	if (vm.count("zone"))
		zoneName = vm["zone"].as<std::string>();

	/* check whether the user wants to generate a new certificate or not */
	String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";

	Log(LogInformation, "cli")
		<< "Checking in existing certificates for common name '" << cn << "'...";

	if (Utility::PathExists(existingPath)) {
		Log(LogWarning, "cli")
			<< "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate.";
	} else {
		Log(LogInformation, "cli")
			<< "Certificates not yet generated. Running 'api setup' now.";

		ApiSetupUtility::SetupMasterCertificates(cn);
	}

	Log(LogInformation, "cli", "Generating master configuration for Icinga 2.");
	ApiSetupUtility::SetupMasterApiUser();

	if (!FeatureUtility::CheckFeatureEnabled("api")) {
		ApiSetupUtility::SetupMasterEnableApi();
	} else {
		Log(LogInformation, "cli")
			<< "'api' feature already enabled.\n";
	}

	/* write zones.conf and update with zone + endpoint information */
	Log(LogInformation, "cli", "Generating zone and object configuration.");

	std::vector<String> globalZones { "global-templates", "director-global" };
	std::vector<std::string> setupGlobalZones;

	if (vm.count("global_zones"))
		setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();

	for (decltype(setupGlobalZones.size()) i = 0; i < setupGlobalZones.size(); i++) {
		if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
			Log(LogCritical, "cli")
				<< "The global zone '" << setupGlobalZones[i] << "' is already specified.";
			return 1;
		}
	}

	globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());

	/* Generate master configuration. */
	NodeUtility::GenerateNodeMasterIcingaConfig(endpointName, zoneName, globalZones);

	/* Update the ApiListener config. */
	Log(LogInformation, "cli", "Updating the APIListener feature.");

	String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
	NodeUtility::CreateBackupFile(apipath);

	AtomicFile fp (apipath, 0644);

	fp << "/**\n"
		<< " * The API listener is used for distributed monitoring setups.\n"
		<< " */\n"
		<< "object ApiListener \"api\" {\n";

	if (vm.count("listen")) {
		std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");

		if (tokens.size() > 0)
			fp << "  bind_host = \"" << tokens[0] << "\"\n";
		if (tokens.size() > 1)
			fp << "  bind_port = " << tokens[1] << "\n";
	}

	fp << "\n";

	if (vm.count("accept-config"))
		fp << "  accept_config = true\n";
	else
		fp << "  accept_config = false\n";

	if (vm.count("accept-commands"))
		fp << "  accept_commands = true\n";
	else
		fp << "  accept_commands = false\n";

	fp << "\n"
		<< "  ticket_salt = TicketSalt\n"
		<< "}\n";

	fp.Commit();

	/* update constants.conf with NodeName = CN + TicketSalt = random value */
	if (endpointName != Utility::GetFQDN()) {
		Log(LogWarning, "cli")
			<< "CN/Endpoint name '" <<  endpointName << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
	}

	NodeUtility::UpdateConstant("NodeName", endpointName);
	NodeUtility::UpdateConstant("ZoneName", zoneName);

	String salt = RandomString(16);

	NodeUtility::UpdateConstant("TicketSalt", salt);

	Log(LogInformation, "cli")
		<< "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";

	if (vm.count("disable-confd")) {
		/* Disable conf.d inclusion */
		if (NodeUtility::UpdateConfiguration("\"conf.d\"", false, true)) {
			Log(LogInformation, "cli")
				<< "Disabled conf.d inclusion";
		} else {
			Log(LogWarning, "cli")
				<< "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
		}

		/* Include api-users.conf */
		String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();

		if (Utility::PathExists(apiUsersFilePath)) {
			NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
		} else {
			Log(LogWarning, "cli")
				<< "Included file doesn't exist " << apiUsersFilePath;
		}
	}

	/* tell the user to reload icinga2 */
	Log(LogInformation, "cli", "Make sure to restart Icinga 2.");

	return 0;
}

int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
{
	/* require at least one endpoint. Ticket is optional. */
	if (!vm.count("endpoint")) {
		Log(LogCritical, "cli", "You need to specify at least one endpoint (--endpoint).");
		return 1;
	}

	if (!vm.count("zone")) {
		Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
		return 1;
	}

	/* Deprecation warnings. TODO: Remove in 2.10.0. */
	if (vm.count("master_zone"))
		Log(LogWarning, "cli", "The 'master_zone' parameter has been deprecated. Use 'parent_zone' instead.");
	if (vm.count("master_host"))
		Log(LogWarning, "cli", "The 'master_host' parameter has been deprecated. Use 'parent_host' instead.");

	String ticket;

	if (vm.count("ticket"))
		ticket = vm["ticket"].as<std::string>();

	if (ticket.IsEmpty()) {
		Log(LogInformation, "cli")
			<< "Requesting certificate without a ticket.";
	} else {
		Log(LogInformation, "cli")
			<< "Requesting certificate with ticket '" << ticket << "'.";
	}

	/* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
	bool connectToParent = false;
	String parentHost;
	String parentPort = "5665";
	std::shared_ptr<X509> trustedParentCert;

	/* TODO: remove master_host in 2.10.0. */
	if (!vm.count("master_host") && !vm.count("parent_host")) {
		connectToParent = false;

		Log(LogWarning, "cli")
			<< "Node to master/satellite connection setup skipped. Please configure your parent node to\n"
			<< "connect to this node by setting the 'host' attribute for the node Endpoint object.\n";
	} else {
		connectToParent = true;

		String parentHostInfo;

		if (vm.count("parent_host"))
			parentHostInfo = vm["parent_host"].as<std::string>();
		else if (vm.count("master_host")) /* TODO: Remove in 2.10.0. */
			parentHostInfo = vm["master_host"].as<std::string>();

		std::vector<String> tokens = parentHostInfo.Split(",");

		if (tokens.size() == 1 || tokens.size() == 2)
			parentHost = tokens[0];

		if (tokens.size() == 2)
			parentPort = tokens[1];

		Log(LogInformation, "cli")
			<< "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";

	}

	/* retrieve CN and pass it (defaults to FQDN) */
	String cn = Utility::GetFQDN();

	if (vm.count("cn"))
		cn = vm["cn"].as<std::string>();

	Log(LogInformation, "cli")
		<< "Using the following CN (defaults to FQDN): '" << cn << "'.";

	/* pki request a signed certificate from the master */
	String certsDir = ApiListener::GetCertsDir();
	Utility::MkDirP(certsDir, 0700);

	String user = Configuration::RunAsUser;
	String group = Configuration::RunAsGroup;

	if (!Utility::SetFileOwnership(certsDir, user, group)) {
		Log(LogWarning, "cli")
			<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << certsDir << "'. Verify it yourself!";
	}

	String key = certsDir + "/" + cn + ".key";
	String cert = certsDir + "/" + cn + ".crt";
	String ca = certsDir + "/ca.crt";

	if (Utility::PathExists(key))
		NodeUtility::CreateBackupFile(key, true);
	if (Utility::PathExists(cert))
		NodeUtility::CreateBackupFile(cert);

	if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
		Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
		return 1;
	}

	/* fix permissions: root -> icinga daemon user */
	if (!Utility::SetFileOwnership(key, user, group)) {
		Log(LogWarning, "cli")
			<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!";
	}

	/* Send a signing request to the parent immediately, or leave it to the user. */
	if (connectToParent) {
		/* In contrast to `node wizard` the user must manually fetch
		 * the trustedParentCert to prove the trust relationship (fetched with 'pki save-cert').
		 */
		if (!vm.count("trustedcert")) {
			Log(LogCritical, "cli")
				<< "Please pass the trusted cert retrieved from the parent node (master or satellite)\n"
				<< "(Hint: 'icinga2 pki save-cert --host <parenthost> --port <5665> --key local.key --cert local.crt --trustedcert trusted-parent.crt').";
			return 1;
		}

		String trustedCert = vm["trustedcert"].as<std::string>();

		try{
			trustedParentCert = GetX509Certificate(trustedCert);
		} catch (const std::exception&) {
			Log(LogCritical, "cli")
				<< "Can't read trusted cert at '" << trustedCert << "'.";
			return 1;
		}

		try {
			if (IsCa(trustedParentCert)) {
				Log(LogCritical, "cli")
					<< "The trusted parent certificate is NOT a client certificate. It seems you passed the 'ca.crt' CA certificate via '--trustedcert' parameter.";
				return 1;
			}
		} catch (const std::exception&) {
			/* Swallow the error and do not run the check on unsupported OpenSSL platforms. */
		}

		Log(LogInformation, "cli")
			<< "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";

		Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");

		if (PkiUtility::RequestCertificate(parentHost, parentPort, key, cert, ca, trustedParentCert, ticket) > 0) {
			Log(LogCritical, "cli")
				<< "Failed to fetch signed certificate from parent Icinga node '"
				<< parentHost << ", "
				<< parentPort << "'. Please try again.";
			return 1;
		}
	} else {
		/* We cannot retrieve the parent certificate.
		 * Tell the user to manually copy the ca.crt file
		 * into DataDir + "/certs"
		 */
		Log(LogWarning, "cli")
			<< "\nNo connection to the parent node was specified.\n\n"
			<< "Please copy the public CA certificate from your master/satellite\n"
			<< "into '" << ca << "' before starting Icinga 2.\n";

		if (Utility::PathExists(ca)) {
			Log(LogInformation, "cli")
				<< "\nFound public CA certificate in '" << ca << "'.\n"
				<< "Please verify that it is the same as on your master/satellite.\n";
		}
	}

	if (!Utility::SetFileOwnership(ca, user, group)) {
		Log(LogWarning, "cli")
			<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!";
	}

	/* fix permissions (again) when updating the signed certificate */
	if (!Utility::SetFileOwnership(cert, user, group)) {
		Log(LogWarning, "cli")
			<< "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!";
	}

	/* disable the notifications feature */
	Log(LogInformation, "cli", "Disabling the Notification feature.");

	FeatureUtility::DisableFeatures({ "notification" });

	/* enable the ApiListener config */

	Log(LogInformation, "cli", "Updating the ApiListener feature.");

	FeatureUtility::EnableFeatures({ "api" });

	String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
	NodeUtility::CreateBackupFile(apipath);

	AtomicFile fp (apipath, 0644);

	fp << "/**\n"
		<< " * The API listener is used for distributed monitoring setups.\n"
		<< " */\n"
		<< "object ApiListener \"api\" {\n";

	if (vm.count("listen")) {
		std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");

		if (tokens.size() > 0)
			fp << "  bind_host = \"" << tokens[0] << "\"\n";
		if (tokens.size() > 1)
			fp << "  bind_port = " << tokens[1] << "\n";
	}

	fp << "\n";

	if (vm.count("accept-config"))
		fp << "  accept_config = true\n";
	else
		fp << "  accept_config = false\n";

	if (vm.count("accept-commands"))
		fp << "  accept_commands = true\n";
	else
		fp << "  accept_commands = false\n";

	fp << "\n"
		<< "}\n";

	fp.Commit();

	/* Generate zones configuration. */
	Log(LogInformation, "cli", "Generating zone and object configuration.");

	/* Setup command hardcodes this as FQDN */
	String endpointName = cn;

	/* Allow to specify zone name. */
	String zoneName = vm["zone"].as<std::string>();

	/* Allow to specify the parent zone name. */
	String parentZoneName = "master";

	if (vm.count("parent_zone"))
		parentZoneName = vm["parent_zone"].as<std::string>();

	std::vector<String> globalZones { "global-templates", "director-global" };
	std::vector<std::string> setupGlobalZones;

	if (vm.count("global_zones"))
		setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();

	for (decltype(setupGlobalZones.size()) i = 0; i < setupGlobalZones.size(); i++) {
		if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
			Log(LogCritical, "cli")
				<< "The global zone '" << setupGlobalZones[i] << "' is already specified.";
			return 1;
		}
	}

	globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());

	/* Generate node configuration. */
	NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);

	/* update constants.conf with NodeName = CN */
	if (endpointName != Utility::GetFQDN()) {
		Log(LogWarning, "cli")
			<< "CN/Endpoint name '" << endpointName << "' does not match the default FQDN '"
			<< Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
	}

	NodeUtility::UpdateConstant("NodeName", endpointName);
	NodeUtility::UpdateConstant("ZoneName", zoneName);

	if (!ticket.IsEmpty()) {
		String ticketPath = ApiListener::GetCertsDir() + "/ticket";
		AtomicFile af (ticketPath, 0600);

		if (!Utility::SetFileOwnership(af.GetTempFilename(), user, group)) {
			Log(LogWarning, "cli")
				<< "Cannot set ownership for user '" << user
				<< "' group '" << group
				<< "' on file '" << ticketPath << "'. Verify it yourself!";
		}

		af << ticket;
		af.Commit();
	}

	/* If no parent connection was made, the user must supply the ca.crt before restarting Icinga 2.*/
	if (!connectToParent) {
		Log(LogWarning, "cli")
			<< "No connection to the parent node was specified.\n\n"
			<< "Please copy the public CA certificate from your master/satellite\n"
			<< "into '" << ca << "' before starting Icinga 2.\n";
	} else {
		Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
	}

	if (vm.count("disable-confd")) {
		/* Disable conf.d inclusion */
		NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
	}

	/* tell the user to reload icinga2 */
	Log(LogInformation, "cli", "Make sure to restart Icinga 2.");

	return 0;
}