summaryrefslogtreecommitdiffstats
path: root/agent/windows-setup-agent/SetupWizard.cs
blob: 327611c4bc84b998b007d62b0f3d38124da6a801 (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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Security.AccessControl;

namespace Icinga
{
	public partial class SetupWizard : Form
	{
		private string _TrustedFile;
		private string Icinga2User;

		public SetupWizard()
		{
			InitializeComponent();

			txtInstanceName.Text = Icinga2InstanceName;

			Icinga2User = Program.Icinga2User;
			txtUser.Text = Icinga2User;
		}

		private void Warning(string message)
		{
			MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
		}

		private string Icinga2InstanceName
		{
			get
			{
				IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties();

				string fqdn = props.HostName;

				if (props.DomainName != "")
					fqdn += "." + props.DomainName;

				return fqdn.ToLower();
			}
		}

		private bool GetMasterHostPort(out string host, out string port)
		{
			foreach (ListViewItem lvi in lvwEndpoints.Items) {
				if (lvi.SubItems.Count > 1) {
					host = lvi.SubItems[1].Text.Trim();
					port = lvi.SubItems[2].Text.Trim();
					return true;
				}
			}

			host = null;
			port = null;
			return false;
		}

		private void EnableFeature(string feature)
		{
			FileStream fp = null;
			try {
				fp = File.Open(Program.Icinga2DataDir + String.Format("\\etc\\icinga2\\features-enabled\\{0}.conf", feature), FileMode.Create);
				using (StreamWriter sw = new StreamWriter(fp, Encoding.ASCII)) {
					fp = null;
					sw.Write(String.Format("include \"../features-available/{0}.conf\"\n", feature));
				}
			} finally {
				if (fp != null)
					fp.Dispose();
			}
		}

		private void SetRetrievalStatus(int pct)
		{
			if (InvokeRequired) {
				Invoke((MethodInvoker)delegate { SetRetrievalStatus(pct); });
				return;
			}

			prgRetrieveCertificate.Value = pct;
		}

		private void SetConfigureStatus(int pct, string message)
		{
			if (InvokeRequired) {
				Invoke((MethodInvoker)delegate { SetConfigureStatus(pct, message); });
				return;
			}

			prgConfig.Value = pct;
			lblConfigStatus.Text = message;
		}

		private void ShowErrorText(string text)
		{
			if (InvokeRequired) {
				Invoke((MethodInvoker)delegate { ShowErrorText(text); });
				return;
			}

			txtError.Text = text;
			tbcPages.SelectedTab = tabError;
		}

		private bool RunProcess(string filename, string arguments, out string output)
		{
			ProcessStartInfo psi = new ProcessStartInfo();
			psi.FileName = filename;
			psi.Arguments = arguments;
			psi.CreateNoWindow = true;
			psi.UseShellExecute = false;
			psi.RedirectStandardOutput = true;
			psi.RedirectStandardError = true;

			String result = "";

			using (Process proc = Process.Start(psi)) {
				proc.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
				{
					result += args.Data + "\r\n";
				};
				proc.OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
				{
					result += args.Data + "\r\n";
				};
				proc.BeginOutputReadLine();
				proc.BeginErrorReadLine();
				proc.WaitForExit();

				output = result;

				if (proc.ExitCode != 0)
					return false;
			}

			return true;
		}

		private void VerifyCertificate(string host, string port)
		{
			SetRetrievalStatus(25);

			string pathPrefix = Program.Icinga2DataDir + "\\etc\\icinga2\\pki\\" + txtInstanceName.Text;
			string processArguments = "pki new-cert --cn \"" + txtInstanceName.Text + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\"";
			string output;

			if (!File.Exists(pathPrefix + ".crt")) {
				if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
					processArguments,
					out output)) {
					ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
					return;
				}
			}

			SetRetrievalStatus(50);

			_TrustedFile = Path.GetTempFileName();

			processArguments = "pki save-cert --host \"" + host + "\" --port \"" + port + "\" --trustedcert \"" + _TrustedFile + "\"";
			if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
				processArguments,
				out output)) {
				ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
				return;
			}

			SetRetrievalStatus(100);
			try {
				X509Certificate2 cert = new X509Certificate2(_TrustedFile);
				Invoke((MethodInvoker)delegate { ShowCertificatePrompt(cert); });
			} catch (Exception e) {
				ShowErrorText("Failed to receive certificate: " + e.Message);
			}
		}

		private void ConfigureService()
		{
			SetConfigureStatus(0, "Updating configuration files...");

			string output;

			string args = "";

			Invoke((MethodInvoker)delegate
			{
				string master_host, master_port;
				GetMasterHostPort(out master_host, out master_port);

				args += " --master_host " + master_host + "," + master_port;

				foreach (ListViewItem lvi in lvwEndpoints.Items) {
					args += " --endpoint " + lvi.SubItems[0].Text.Trim();

					if (lvi.SubItems.Count > 1)
						args += "," + lvi.SubItems[1].Text.Trim() + "," + lvi.SubItems[2].Text.Trim();
				}
			});

			if (rdoListener.Checked)
				args += " --listen ::," + txtListenerPort.Text.Trim();

			if (chkAcceptConfig.Checked)
				args += " --accept-config";

			if (chkAcceptCommands.Checked)
				args += " --accept-commands";

			string ticket = txtTicket.Text.Trim();

			if (ticket.Length > 0)
				args += " --ticket \"" + ticket + "\"";

			args += " --trustedcert \"" + _TrustedFile + "\"";
			args += " --cn \"" + txtInstanceName.Text.Trim() + "\"";
			args += " --zone \"" + txtInstanceName.Text.Trim() + "\"";

			foreach (ListViewItem lvi in lvwGlobalZones.Items) {
				args += " --global_zones " + lvi.SubItems[0].Text.Trim();
			}

			if (chkDisableConf.Checked)
				args += " --disable-confd";

			if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
				"node setup" + args,
				out output)) {
				ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
				return;
			}

			SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");

			string serviceUser = txtUser.Text.Trim();

			DirectoryInfo di = new DirectoryInfo(Program.Icinga2InstallDir);
			DirectorySecurity ds = di.GetAccessControl();
			FileSystemAccessRule rule = new FileSystemAccessRule(serviceUser,
				FileSystemRights.Modify,
				InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
			try {
				ds.AddAccessRule(rule);
				di.SetAccessControl(ds);
			} catch (System.Security.Principal.IdentityNotMappedException) {
				ShowErrorText("Could not set ACLs for user \"" + serviceUser + "\". Identitiy is not mapped.\n");
				return;
			}

			SetConfigureStatus(75, "Installing the Icinga 2 service...");

			RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
				"--scm-uninstall",
				out output);

			if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
				"daemon --validate",
				out output)) {
				ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
				return;
			}

			if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
				"--scm-install --scm-user \"" + serviceUser + "\" daemon",
				out output)) {
				ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
					serviceUser + "\" daemon' produced the following output:\n" + output);
				return;
			}

			SetConfigureStatus(100, "Finished.");

			// Override the completed text
			lblSetupCompleted.Text = "The Icinga Windows agent was set up successfully.";

			// Add a note for the user for ticket-less signing
			if (ticket.Length == 0) {
				lblSetupCompleted.Text += "\n\nTicket was not specified. Please sign the certificate request on the Icinga 2 master node (requires v2.8+).";
			}

			FinishConfigure();
		}

		private void FinishConfigure()
		{
			if (InvokeRequired) {
				Invoke((MethodInvoker)FinishConfigure);
				return;
			}

			tbcPages.SelectedTab = tabFinish;
		}

		private void btnBack_Click(object sender, EventArgs e)
		{
			if (tbcPages.SelectedTab == tabError) {
				tbcPages.SelectedIndex = 0;
				return;
			}

			int offset = 1;

			if (tbcPages.SelectedTab == tabVerifyCertificate)
				offset++;

			tbcPages.SelectedIndex -= offset;
		}

		private void btnNext_Click(object sender, EventArgs e)
		{
			if (tbcPages.SelectedTab == tabParameters) {
				if (txtInstanceName.Text.Length == 0) {
					Warning("Please enter an instance name.");
					return;
				}

				if (lvwEndpoints.Items.Count == 0) {
					Warning("You need to add at least one master/satellite endpoint.");
					return;
				}

				string host, port;
				if (!GetMasterHostPort(out host, out port)) {
					Warning("Please enter a remote host and port for at least one of your endpoints.");
					return;
				}

				if (rdoListener.Checked && (txtListenerPort.Text == "")) {
					Warning("You need to specify a listener port.");
					return;
				}

				if (txtUser.Text.Length == 0) {
					Warning("Icinga 2 service user may not be empty.");
					return;
				}
			}

			if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
				Application.Exit();

			tbcPages.SelectedIndex++;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
		{
			Refresh();

			btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
			btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);

			if (tbcPages.SelectedTab == tabFinish) {
				btnNext.Text = "&Finish >";
				btnCancel.Enabled = false;
			}

			if (tbcPages.SelectedTab == tabRetrieveCertificate) {
				ListViewItem lvi = lvwEndpoints.Items[0];

				string master_host, master_port;
				GetMasterHostPort(out master_host, out master_port);

				Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
				thread.Start();
			}

			if (tbcPages.SelectedTab == tabConfigure) {
				Thread thread = new Thread(ConfigureService);
				thread.Start();
			}
		}

		private void RadioListener_CheckedChanged(object sender, EventArgs e)
		{
			txtListenerPort.Enabled = rdoListener.Checked;
		}

		private void AddCertificateField(string name, string shortValue, string longValue = null)
		{
			ListViewItem lvi = new ListViewItem();
			lvi.Text = name;
			lvi.SubItems.Add(shortValue);
			if (longValue == null)
				longValue = shortValue;
			lvi.Tag = longValue;
			lvwX509Fields.Items.Add(lvi);
		}

		private string PadText(string input)
		{
			string output = "";

			for (int i = 0; i < input.Length; i += 2) {
				if (output != "")
					output += " ";

				int len = 2;
				if (input.Length - i < 2)
					len = input.Length - i;
				output += input.Substring(i, len);
			}

			return output;
		}

		private void ShowCertificatePrompt(X509Certificate2 certificate)
		{
			txtX509Issuer.Text = certificate.Issuer;
			txtX509Subject.Text = certificate.Subject;

			lvwX509Fields.Items.Clear();

			AddCertificateField("Version", "V" + certificate.Version.ToString());
			AddCertificateField("Serial number", certificate.SerialNumber);
			AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
			AddCertificateField("Valid from", certificate.NotBefore.ToString());
			AddCertificateField("Valid to", certificate.NotAfter.ToString());

			string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
			AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);

			string thumbprint = PadText(certificate.Thumbprint);
			AddCertificateField("Thumbprint", thumbprint);

			tbcPages.SelectedTab = tabVerifyCertificate;
		}

		private void btnAddEndpoint_Click(object sender, EventArgs e)
		{
			EndpointInputBox eib = new EndpointInputBox();

			if (eib.ShowDialog(this) == DialogResult.Cancel)
				return;

			ListViewItem lvi = new ListViewItem();
			lvi.Text = eib.txtInstanceName.Text;

			if (eib.chkConnect.Checked) {
				lvi.SubItems.Add(eib.txtHost.Text);
				lvi.SubItems.Add(eib.txtPort.Text);
			}

			lvwEndpoints.Items.Add(lvi);
		}

		private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
		{
			btnRemoveEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
			btnEditEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
		}

		private void lvwX509Fields_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (lvwX509Fields.SelectedItems.Count == 0)
				return;

			ListViewItem lvi = lvwX509Fields.SelectedItems[0];

			txtX509Field.Text = Convert.ToString(lvi.Tag);
		}

		private void btnRemoveEndpoint_Click(object sender, EventArgs e)
		{
			while (lvwEndpoints.SelectedItems.Count > 0) {
				lvwEndpoints.Items.Remove(lvwEndpoints.SelectedItems[0]);
			}
		}

		private void chkRunServiceAsThisUser_CheckedChanged(object sender, EventArgs e)
		{
			txtUser.Enabled = !txtUser.Enabled;
			if (!txtUser.Enabled)
				txtUser.Text = Icinga2User;
		}

		private void btnEditEndpoint_Click(object sender, EventArgs e)
		{
			ListViewItem lvi = lvwEndpoints.SelectedItems[0];
			EndpointInputBox eib = new EndpointInputBox();

			eib.Text = "Edit Endpoint";
			eib.txtInstanceName.Text = lvi.SubItems[0].Text;

			if (lvi.SubItems.Count >= 2) {
				eib.txtHost.Text = lvi.SubItems[1].Text;
				eib.txtPort.Text = lvi.SubItems[2].Text;
				eib.chkConnect.Checked = true;
			}

			if (eib.ShowDialog(this) == DialogResult.Cancel)
				return;

			lvwEndpoints.Items.Remove(lvi);

			ListViewItem lvi2 = new ListViewItem();
			lvi2.Text = eib.txtInstanceName.Text;

			if (eib.chkConnect.Checked) {
				lvi2.SubItems.Add(eib.txtHost.Text);
				lvi2.SubItems.Add(eib.txtPort.Text);
			}

			lvwEndpoints.Items.Add(lvi2);
		}

		private void btnAddGlobalZone_Click(object sender, EventArgs e)
		{
			GlobalZonesInputBox gzib = new GlobalZonesInputBox(lvwGlobalZones.Items);

			if (gzib.ShowDialog(this) == DialogResult.Cancel)
				return;

			ListViewItem lvi = new ListViewItem();
			lvi.Text = gzib.txtGlobalZoneName.Text;

			lvwGlobalZones.Items.Add(lvi);
		}

		private void btnRemoveGlobalZone_Click(object sender, EventArgs e)
		{
			while (lvwGlobalZones.SelectedItems.Count > 0) {
				lvwGlobalZones.Items.Remove(lvwGlobalZones.SelectedItems[0]);
			}
		}

		private void lvwGlobalZones_SelectedIndexChanged(object sender, EventArgs e)
		{
			btnEditGlobalZone.Enabled = lvwGlobalZones.SelectedItems.Count > 0;
			btnRemoveGlobalZone.Enabled = lvwGlobalZones.SelectedItems.Count > 0;
		}

		private void btnEditGlobalZone_Click(object sender, EventArgs e)
		{
			ListViewItem lvi = lvwGlobalZones.SelectedItems[0];
			GlobalZonesInputBox gzib = new GlobalZonesInputBox(lvwGlobalZones.Items);

			gzib.Text = "Edit Global Zone";
			gzib.txtGlobalZoneName.Text = lvi.SubItems[0].Text;
			
			if (gzib.ShowDialog(this) == DialogResult.Cancel)
				return;

			lvwGlobalZones.Items.Remove(lvi);

			ListViewItem lvi2 = new ListViewItem();
			lvi2.Text = gzib.txtGlobalZoneName.Text;
			
			lvwGlobalZones.Items.Add(lvi2);
		}

		private void SetupWizard_Load(object sender, EventArgs e)
		{
			this.MinimumSize = this.Size;
			this.MaximumSize = this.Size;
		}

		private void linkLabelDocs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			linkLabelDocs.LinkVisited = true;

			Process.Start("https://icinga.com/docs/icinga2/latest/");
		}
	}
}