]> granicus.if.org Git - icinga2/blob - agent/windows-setup-agent/SetupWizard.cs
Add option to windows installer to add global zones
[icinga2] / agent / windows-setup-agent / SetupWizard.cs
1 using System;
2 using System.IO;
3 using System.Text;
4 using System.Collections.Generic;
5 using System.ComponentModel;
6 using System.Windows.Forms;
7 using System.Runtime.InteropServices;
8 using System.Security.Cryptography.X509Certificates;
9 using System.Threading;
10 using System.Net.NetworkInformation;
11 using System.IO.Compression;
12 using System.Diagnostics;
13 using System.ServiceProcess;
14 using System.Security.AccessControl;
15
16 namespace Icinga
17 {
18         public partial class SetupWizard : Form
19         {
20                 private string _TrustedFile;
21                 private string Icinga2User;
22
23                 public SetupWizard()
24                 {
25                         InitializeComponent();
26
27                         txtInstanceName.Text = Icinga2InstanceName;
28
29                         Icinga2User = Program.Icinga2User;
30                         txtUser.Text = Icinga2User;
31                 }
32
33                 private void Warning(string message)
34                 {
35                         MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
36                 }
37
38                 private string Icinga2InstanceName
39                 {
40                         get
41                         {
42                                 IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties();
43
44                                 string fqdn = props.HostName;
45
46                                 if (props.DomainName != "")
47                                         fqdn += "." + props.DomainName;
48
49                                 return fqdn;
50                         }
51                 }
52
53                 private bool GetMasterHostPort(out string host, out string port)
54                 {
55                         foreach (ListViewItem lvi in lvwEndpoints.Items) {
56                                 if (lvi.SubItems.Count > 1) {
57                                         host = lvi.SubItems[1].Text.Trim();
58                                         port = lvi.SubItems[2].Text.Trim();
59                                         return true;
60                                 }
61                         }
62
63                         host = null;
64                         port = null;
65                         return false;
66                 }
67
68                 private void EnableFeature(string feature)
69                 {
70                         FileStream fp = null;
71                         try {
72                                 fp = File.Open(Program.Icinga2DataDir + String.Format("\\etc\\icinga2\\features-enabled\\{0}.conf", feature), FileMode.Create);
73                                 using (StreamWriter sw = new StreamWriter(fp, Encoding.ASCII)) {
74                                         fp = null;
75                                         sw.Write(String.Format("include \"../features-available/{0}.conf\"\n", feature));
76                                 }
77                         } finally {
78                                 if (fp != null)
79                                         fp.Dispose();
80                         }
81                 }
82
83                 private void SetRetrievalStatus(int pct)
84                 {
85                         if (InvokeRequired) {
86                                 Invoke((MethodInvoker)delegate { SetRetrievalStatus(pct); });
87                                 return;
88                         }
89
90                         prgRetrieveCertificate.Value = pct;
91                 }
92
93                 private void SetConfigureStatus(int pct, string message)
94                 {
95                         if (InvokeRequired) {
96                                 Invoke((MethodInvoker)delegate { SetConfigureStatus(pct, message); });
97                                 return;
98                         }
99
100                         prgConfig.Value = pct;
101                         lblConfigStatus.Text = message;
102                 }
103
104                 private void ShowErrorText(string text)
105                 {
106                         if (InvokeRequired) {
107                                 Invoke((MethodInvoker)delegate { ShowErrorText(text); });
108                                 return;
109                         }
110
111                         txtError.Text = text;
112                         tbcPages.SelectedTab = tabError;
113                 }
114
115                 private bool RunProcess(string filename, string arguments, out string output)
116                 {
117                         ProcessStartInfo psi = new ProcessStartInfo();
118                         psi.FileName = filename;
119                         psi.Arguments = arguments;
120                         psi.CreateNoWindow = true;
121                         psi.UseShellExecute = false;
122                         psi.RedirectStandardOutput = true;
123                         psi.RedirectStandardError = true;
124
125                         String result = "";
126
127                         using (Process proc = Process.Start(psi)) {
128                                 proc.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
129                                 {
130                                         result += args.Data + "\r\n";
131                                 };
132                                 proc.OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
133                                 {
134                                         result += args.Data + "\r\n";
135                                 };
136                                 proc.BeginOutputReadLine();
137                                 proc.BeginErrorReadLine();
138                                 proc.WaitForExit();
139
140                                 output = result;
141
142                                 if (proc.ExitCode != 0)
143                                         return false;
144                         }
145
146                         return true;
147                 }
148
149                 private void VerifyCertificate(string host, string port)
150                 {
151                         SetRetrievalStatus(25);
152
153                         string pathPrefix = Program.Icinga2DataDir + "\\etc\\icinga2\\pki\\" + txtInstanceName.Text;
154                         string processArguments = "pki new-cert --cn \"" + txtInstanceName.Text + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\"";
155                         string output;
156
157                         if (!File.Exists(pathPrefix + ".crt")) {
158                                 if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
159                                         processArguments,
160                                         out output)) {
161                                         ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
162                                         return;
163                                 }
164                         }
165
166                         SetRetrievalStatus(50);
167
168                         _TrustedFile = Path.GetTempFileName();
169
170                         processArguments = "pki save-cert --host \"" + host + "\" --port \"" + port + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\" --trustedcert \"" + _TrustedFile + "\"";
171                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
172                                 processArguments,
173                                 out output)) {
174                                 ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
175                                 return;
176                         }
177
178                         SetRetrievalStatus(100);
179
180                         X509Certificate2 cert = new X509Certificate2(_TrustedFile);
181                         Invoke((MethodInvoker)delegate { ShowCertificatePrompt(cert); });
182                 }
183
184                 private void ConfigureService()
185                 {
186                         SetConfigureStatus(0, "Updating configuration files...");
187
188                         string output;
189
190                         string args = "";
191
192                         Invoke((MethodInvoker)delegate
193                         {
194                                 string master_host, master_port;
195                                 GetMasterHostPort(out master_host, out master_port);
196
197                                 args += " --master_host " + master_host + "," + master_port;
198
199                                 foreach (ListViewItem lvi in lvwEndpoints.Items) {
200                                         args += " --endpoint " + lvi.SubItems[0].Text.Trim();
201
202                                         if (lvi.SubItems.Count > 1)
203                                                 args += "," + lvi.SubItems[1].Text.Trim() + "," + lvi.SubItems[2].Text.Trim();
204                                 }
205                         });
206
207                         if (rdoListener.Checked)
208                                 args += " --listen ::," + txtListenerPort.Text.Trim();
209
210                         if (chkAcceptConfig.Checked)
211                                 args += " --accept-config";
212
213                         if (chkAcceptCommands.Checked)
214                                 args += " --accept-commands";
215
216                         string ticket = txtTicket.Text.Trim();
217
218                         if (ticket.Length > 0)
219                                 args += " --ticket \"" + ticket + "\"";
220
221                         args += " --trustedcert \"" + _TrustedFile + "\"";
222                         args += " --cn \"" + txtInstanceName.Text.Trim() + "\"";
223                         args += " --zone \"" + txtInstanceName.Text.Trim() + "\"";
224
225                         foreach (ListViewItem lvi in lvwGlobalZones.Items) {
226                                 args += " --global_zones " + lvi.SubItems[0].Text.Trim();
227                         }
228
229                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
230                                 "node setup" + args,
231                                 out output)) {
232                                 ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
233                                 return;
234                         }
235
236                         SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
237
238                         string serviceUser = txtUser.Text.Trim();
239
240                         DirectoryInfo di = new DirectoryInfo(Program.Icinga2InstallDir);
241                         DirectorySecurity ds = di.GetAccessControl();
242                         FileSystemAccessRule rule = new FileSystemAccessRule(serviceUser,
243                                 FileSystemRights.Modify,
244                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
245                         try {
246                                 ds.AddAccessRule(rule);
247                                 di.SetAccessControl(ds);
248                         } catch (System.Security.Principal.IdentityNotMappedException) {
249                                 ShowErrorText("Could not set ACLs for user \"" + serviceUser + "\". Identitiy is not mapped.\n");
250                                 return;
251                         }
252
253                         SetConfigureStatus(75, "Installing the Icinga 2 service...");
254
255                         RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
256                                 "--scm-uninstall",
257                                 out output);
258
259                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
260                                 "daemon --validate",
261                                 out output)) {
262                                 ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
263                                 return;
264                         }
265
266                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
267                                 "--scm-install --scm-user \"" + serviceUser + "\" daemon",
268                                 out output)) {
269                                 ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
270                                         serviceUser + "\" daemon' produced the following output:\n" + output);
271                                 return;
272                         }
273
274                         if (chkInstallNSCP.Checked) {
275                                 SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");
276
277                                 Process proc = new Process();
278                                 proc.StartInfo.FileName = "msiexec.exe";
279                                 proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP.msi\"";
280                                 proc.Start();
281                                 proc.WaitForExit();
282                         }
283
284                         SetConfigureStatus(100, "Finished.");
285
286                         // Override the completed text
287                         lblSetupCompleted.Text = "The Icinga 2 Windows client was set up successfully.";
288
289                         // Add a note for the user for ticket-less signing
290                         if (ticket.Length == 0) {
291                                 lblSetupCompleted.Text += "\n\nTicket was not specified. Please sign the certificate request on the Icinga 2 master node (requires v2.8+).";
292                         }
293
294                         FinishConfigure();
295                 }
296
297                 private void FinishConfigure()
298                 {
299                         if (InvokeRequired) {
300                                 Invoke((MethodInvoker)FinishConfigure);
301                                 return;
302                         }
303
304                         tbcPages.SelectedTab = tabFinish;
305                 }
306
307                 private void btnBack_Click(object sender, EventArgs e)
308                 {
309                         if (tbcPages.SelectedTab == tabError) {
310                                 tbcPages.SelectedIndex = 0;
311                                 return;
312                         }
313
314                         int offset = 1;
315
316                         if (tbcPages.SelectedTab == tabVerifyCertificate)
317                                 offset++;
318
319                         tbcPages.SelectedIndex -= offset;
320                 }
321
322                 private void btnNext_Click(object sender, EventArgs e)
323                 {
324                         if (tbcPages.SelectedTab == tabParameters) {
325                                 if (txtInstanceName.Text.Length == 0) {
326                                         Warning("Please enter an instance name.");
327                                         return;
328                                 }
329
330                                 if (lvwEndpoints.Items.Count == 0) {
331                                         Warning("You need to add at least one master/satellite endpoint.");
332                                         return;
333                                 }
334
335                                 string host, port;
336                                 if (!GetMasterHostPort(out host, out port)) {
337                                         Warning("Please enter a remote host and port for at least one of your endpoints.");
338                                         return;
339                                 }
340
341                                 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
342                                         Warning("You need to specify a listener port.");
343                                         return;
344                                 }
345
346                                 if (txtUser.Text.Length == 0) {
347                                         Warning("Icinga 2 service user may not be empty.");
348                                         return;
349                                 }
350                         }
351
352                         if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
353                                 Application.Exit();
354
355                         tbcPages.SelectedIndex++;
356                 }
357
358                 private void btnCancel_Click(object sender, EventArgs e)
359                 {
360                         Application.Exit();
361                 }
362
363                 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
364                 {
365                         Refresh();
366
367                         btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
368                         btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
369
370                         if (tbcPages.SelectedTab == tabFinish) {
371                                 btnNext.Text = "&Finish >";
372                                 btnCancel.Enabled = false;
373                         }
374
375                         if (tbcPages.SelectedTab == tabRetrieveCertificate) {
376                                 ListViewItem lvi = lvwEndpoints.Items[0];
377
378                                 string master_host, master_port;
379                                 GetMasterHostPort(out master_host, out master_port);
380
381                                 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
382                                 thread.Start();
383                         }
384
385                         if (tbcPages.SelectedTab == tabConfigure) {
386                                 Thread thread = new Thread(ConfigureService);
387                                 thread.Start();
388                         }
389                 }
390
391                 private void RadioListener_CheckedChanged(object sender, EventArgs e)
392                 {
393                         txtListenerPort.Enabled = rdoListener.Checked;
394                 }
395
396                 private void AddCertificateField(string name, string shortValue, string longValue = null)
397                 {
398                         ListViewItem lvi = new ListViewItem();
399                         lvi.Text = name;
400                         lvi.SubItems.Add(shortValue);
401                         if (longValue == null)
402                                 longValue = shortValue;
403                         lvi.Tag = longValue;
404                         lvwX509Fields.Items.Add(lvi);
405                 }
406
407                 private string PadText(string input)
408                 {
409                         string output = "";
410
411                         for (int i = 0; i < input.Length; i += 2) {
412                                 if (output != "")
413                                         output += " ";
414
415                                 int len = 2;
416                                 if (input.Length - i < 2)
417                                         len = input.Length - i;
418                                 output += input.Substring(i, len);
419                         }
420
421                         return output;
422                 }
423
424                 private void ShowCertificatePrompt(X509Certificate2 certificate)
425                 {
426                         txtX509Issuer.Text = certificate.Issuer;
427                         txtX509Subject.Text = certificate.Subject;
428
429                         lvwX509Fields.Items.Clear();
430
431                         AddCertificateField("Version", "V" + certificate.Version.ToString());
432                         AddCertificateField("Serial number", certificate.SerialNumber);
433                         AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
434                         AddCertificateField("Valid from", certificate.NotBefore.ToString());
435                         AddCertificateField("Valid to", certificate.NotAfter.ToString());
436
437                         string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
438                         AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);
439
440                         string thumbprint = PadText(certificate.Thumbprint);
441                         AddCertificateField("Thumbprint", thumbprint);
442
443                         tbcPages.SelectedTab = tabVerifyCertificate;
444                 }
445
446                 private void btnAddEndpoint_Click(object sender, EventArgs e)
447                 {
448                         EndpointInputBox eib = new EndpointInputBox();
449
450                         if (eib.ShowDialog(this) == DialogResult.Cancel)
451                                 return;
452
453                         ListViewItem lvi = new ListViewItem();
454                         lvi.Text = eib.txtInstanceName.Text;
455
456                         if (eib.chkConnect.Checked) {
457                                 lvi.SubItems.Add(eib.txtHost.Text);
458                                 lvi.SubItems.Add(eib.txtPort.Text);
459                         }
460
461                         lvwEndpoints.Items.Add(lvi);
462                 }
463
464                 private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
465                 {
466                         btnRemoveEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
467                         btnEditEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
468                 }
469
470                 private void lvwX509Fields_SelectedIndexChanged(object sender, EventArgs e)
471                 {
472                         if (lvwX509Fields.SelectedItems.Count == 0)
473                                 return;
474
475                         ListViewItem lvi = lvwX509Fields.SelectedItems[0];
476
477                         txtX509Field.Text = Convert.ToString(lvi.Tag);
478                 }
479
480                 private void btnRemoveEndpoint_Click(object sender, EventArgs e)
481                 {
482                         while (lvwEndpoints.SelectedItems.Count > 0) {
483                                 lvwEndpoints.Items.Remove(lvwEndpoints.SelectedItems[0]);
484                         }
485                 }
486
487                 private void chkRunServiceAsThisUser_CheckedChanged(object sender, EventArgs e)
488                 {
489                         txtUser.Enabled = !txtUser.Enabled;
490                         if (!txtUser.Enabled)
491                                 txtUser.Text = Icinga2User;
492                 }
493
494                 private void btnEditEndpoint_Click(object sender, EventArgs e)
495                 {
496                         ListViewItem lvi = lvwEndpoints.SelectedItems[0];
497                         EndpointInputBox eib = new EndpointInputBox();
498
499                         eib.Text = "Edit Endpoint";
500                         eib.txtInstanceName.Text = lvi.SubItems[0].Text;
501
502                         if (lvi.SubItems.Count >= 2) {
503                                 eib.txtHost.Text = lvi.SubItems[1].Text;
504                                 eib.txtPort.Text = lvi.SubItems[2].Text;
505                                 eib.chkConnect.Checked = true;
506                         }
507
508                         if (eib.ShowDialog(this) == DialogResult.Cancel)
509                                 return;
510
511                         lvwEndpoints.Items.Remove(lvi);
512
513                         ListViewItem lvi2 = new ListViewItem();
514                         lvi2.Text = eib.txtInstanceName.Text;
515
516                         if (eib.chkConnect.Checked) {
517                                 lvi2.SubItems.Add(eib.txtHost.Text);
518                                 lvi2.SubItems.Add(eib.txtPort.Text);
519                         }
520
521                         lvwEndpoints.Items.Add(lvi2);
522                 }
523
524                 private void btnAddGlobalZone_Click(object sender, EventArgs e)
525                 {
526                         GlobalZonesInputBox gzib = new GlobalZonesInputBox(lvwGlobalZones.Items);
527
528                         if (gzib.ShowDialog(this) == DialogResult.Cancel)
529                                 return;
530
531                         ListViewItem lvi = new ListViewItem();
532                         lvi.Text = gzib.txtGlobalZoneName.Text;
533
534                         lvwGlobalZones.Items.Add(lvi);
535                 }
536
537                 private void btnRemoveGlobalZone_Click(object sender, EventArgs e)
538                 {
539                         while (lvwGlobalZones.SelectedItems.Count > 0) {
540                                 lvwGlobalZones.Items.Remove(lvwGlobalZones.SelectedItems[0]);
541                         }
542                 }
543
544                 private void lvwGlobalZones_SelectedIndexChanged(object sender, EventArgs e)
545                 {
546                         btnEditGlobalZone.Enabled = lvwGlobalZones.SelectedItems.Count > 0;
547                         btnRemoveGlobalZone.Enabled = lvwGlobalZones.SelectedItems.Count > 0;
548                 }
549
550                 private void btnEditGlobalZone_Click(object sender, EventArgs e)
551                 {
552                         ListViewItem lvi = lvwGlobalZones.SelectedItems[0];
553                         GlobalZonesInputBox gzib = new GlobalZonesInputBox(lvwGlobalZones.Items);
554
555                         gzib.Text = "Edit Global Zone";
556                         gzib.txtGlobalZoneName.Text = lvi.SubItems[0].Text;
557                         
558                         if (gzib.ShowDialog(this) == DialogResult.Cancel)
559                                 return;
560
561                         lvwGlobalZones.Items.Remove(lvi);
562
563                         ListViewItem lvi2 = new ListViewItem();
564                         lvi2.Text = gzib.txtGlobalZoneName.Text;
565                         
566                         lvwGlobalZones.Items.Add(lvi2);
567                 }
568         }
569 }
570