]> granicus.if.org Git - icinga2/blob - agent/windows-setup-agent/SetupWizard.cs
Windows Wizard: Finalize design for 2.8
[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;
58                                         port = lvi.SubItems[2].Text;
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 " + Convert.ToString(master_host).Trim()
198                                     + "," + Convert.ToString(master_port).Trim();
199
200                                 foreach (ListViewItem lvi in lvwEndpoints.Items) {
201                                         args += " --endpoint " + Convert.ToString(lvi.SubItems[0].Text).Trim();
202
203                                         if (lvi.SubItems.Count > 1) {
204                                                 args += "," + Convert.ToString(lvi.SubItems[1].Text).Trim()
205                                                     + "," + Convert.ToString(lvi.SubItems[2].Text).Trim();
206                                         }
207                                 }
208                         });
209
210                         if (rdoListener.Checked)
211                                 args += " --listen ::," + Convert.ToString(txtListenerPort.Text).Trim();
212
213                         if (chkAcceptConfig.Checked)
214                                 args += " --accept-config";
215
216                         if (chkAcceptCommands.Checked)
217                                 args += " --accept-commands";
218
219                         string ticket = Convert.ToString(txtTicket.Text).Trim();
220
221                         if (ticket.Length > 0)
222                                 args += " --ticket \"" + ticket + "\"";
223
224                         args += " --trustedcert \"" + _TrustedFile + "\"";
225                         args += " --cn \"" + Convert.ToString(txtInstanceName.Text).Trim() + "\"";
226                         args += " --zone \"" + Convert.ToString(txtInstanceName.Text) + "\"";
227
228                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
229                                 "node setup" + args,
230                                 out output)) {
231                                 ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
232                                 return;
233                         }
234
235                         SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
236
237                         string serviceUser = Convert.ToString(txtUser.Text).Trim();
238
239                         DirectoryInfo di = new DirectoryInfo(Program.Icinga2InstallDir);
240                         DirectorySecurity ds = di.GetAccessControl();
241                         FileSystemAccessRule rule = new FileSystemAccessRule(serviceUser,
242                                 FileSystemRights.Modify,
243                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
244                         try {
245                                 ds.AddAccessRule(rule);
246                                 di.SetAccessControl(ds);
247                         } catch (System.Security.Principal.IdentityNotMappedException) {
248                                 ShowErrorText("Could not set ACLs for user \"" + serviceUser + "\". Identitiy is not mapped.\n");
249                                 return;
250                         }
251
252                         SetConfigureStatus(75, "Installing the Icinga 2 service...");
253
254                         RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
255                                 "--scm-uninstall",
256                                 out output);
257
258                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
259                                 "daemon --validate",
260                                 out output)) {
261                                 ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
262                                 return;
263                         }
264
265                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
266                                 "--scm-install --scm-user \"" + serviceUser + "\" daemon",
267                                 out output)) {
268                                 ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
269                                         serviceUser + "\" daemon' produced the following output:\n" + output);
270                                 return;
271                         }
272
273                         if (chkInstallNSCP.Checked) {
274                                 SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");
275
276                                 Process proc = new Process();
277                                 proc.StartInfo.FileName = "msiexec.exe";
278                                 proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP.msi\"";
279                                 proc.Start();
280                                 proc.WaitForExit();
281                         }
282
283                         SetConfigureStatus(100, "Finished.");
284
285                         // Override the completed text
286                         lblSetupCompleted.Text = "The Icinga 2 Windows client was set up successfully.";
287
288                         // Add a note for the user for ticket-less signing
289                         if (ticket.Length == 0) {
290                                 lblSetupCompleted.Text += "\n\nTicket was not specified. Please sign the certificate request on the Icinga 2 master node (requires v2.8+).";
291                         }
292
293                         FinishConfigure();
294                 }
295
296                 private void FinishConfigure()
297                 {
298                         if (InvokeRequired) {
299                                 Invoke((MethodInvoker)FinishConfigure);
300                                 return;
301                         }
302
303                         tbcPages.SelectedTab = tabFinish;
304                 }
305
306                 private void btnBack_Click(object sender, EventArgs e)
307                 {
308                         if (tbcPages.SelectedTab == tabError) {
309                                 tbcPages.SelectedIndex = 0;
310                                 return;
311                         }
312
313                         int offset = 1;
314
315                         if (tbcPages.SelectedTab == tabVerifyCertificate)
316                                 offset++;
317
318                         tbcPages.SelectedIndex -= offset;
319                 }
320
321                 private void btnNext_Click(object sender, EventArgs e)
322                 {
323                         if (tbcPages.SelectedTab == tabParameters) {
324                                 if (txtInstanceName.Text.Length == 0) {
325                                         Warning("Please enter an instance name.");
326                                         return;
327                                 }
328
329                                 if (lvwEndpoints.Items.Count == 0) {
330                                         Warning("You need to add at least one master/satellite endpoint.");
331                                         return;
332                                 }
333
334                                 string host, port;
335                                 if (!GetMasterHostPort(out host, out port)) {
336                                         Warning("Please enter a remote host and port for at least one of your endpoints.");
337                                         return;
338                                 }
339
340                                 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
341                                         Warning("You need to specify a listener port.");
342                                         return;
343                                 }
344
345                                 if (txtUser.Text.Length == 0) {
346                                         Warning("Icinga 2 service user may not be empty.");
347                                         return;
348                                 }
349                         }
350
351                         if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
352                                 Application.Exit();
353
354                         tbcPages.SelectedIndex++;
355                 }
356
357                 private void btnCancel_Click(object sender, EventArgs e)
358                 {
359                         Application.Exit();
360                 }
361
362                 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
363                 {
364                         Refresh();
365
366                         btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
367                         btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
368
369                         if (tbcPages.SelectedTab == tabFinish) {
370                                 btnNext.Text = "&Finish >";
371                                 btnCancel.Enabled = false;
372                         }
373
374                         if (tbcPages.SelectedTab == tabRetrieveCertificate) {
375                                 ListViewItem lvi = lvwEndpoints.Items[0];
376
377                                 string master_host, master_port;
378                                 GetMasterHostPort(out master_host, out master_port);
379
380                                 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
381                                 thread.Start();
382                         }
383
384                         if (tbcPages.SelectedTab == tabConfigure) {
385                                 Thread thread = new Thread(ConfigureService);
386                                 thread.Start();
387                         }
388                 }
389
390                 private void RadioListener_CheckedChanged(object sender, EventArgs e)
391                 {
392                         txtListenerPort.Enabled = rdoListener.Checked;
393                 }
394
395                 private void AddCertificateField(string name, string shortValue, string longValue = null)
396                 {
397                         ListViewItem lvi = new ListViewItem();
398                         lvi.Text = name;
399                         lvi.SubItems.Add(shortValue);
400                         if (longValue == null)
401                                 longValue = shortValue;
402                         lvi.Tag = longValue;
403                         lvwX509Fields.Items.Add(lvi);
404                 }
405
406                 private string PadText(string input)
407                 {
408                         string output = "";
409
410                         for (int i = 0; i < input.Length; i += 2) {
411                                 if (output != "")
412                                         output += " ";
413
414                                 int len = 2;
415                                 if (input.Length - i < 2)
416                                         len = input.Length - i;
417                                 output += input.Substring(i, len);
418                         }
419
420                         return output;
421                 }
422
423                 private void ShowCertificatePrompt(X509Certificate2 certificate)
424                 {
425                         txtX509Issuer.Text = certificate.Issuer;
426                         txtX509Subject.Text = certificate.Subject;
427
428                         lvwX509Fields.Items.Clear();
429
430                         AddCertificateField("Version", "V" + certificate.Version.ToString());
431                         AddCertificateField("Serial number", certificate.SerialNumber);
432                         AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
433                         AddCertificateField("Valid from", certificate.NotBefore.ToString());
434                         AddCertificateField("Valid to", certificate.NotAfter.ToString());
435
436                         string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
437                         AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);
438
439                         string thumbprint = PadText(certificate.Thumbprint);
440                         AddCertificateField("Thumbprint", thumbprint);
441
442                         tbcPages.SelectedTab = tabVerifyCertificate;
443                 }
444
445                 private void btnAddEndpoint_Click(object sender, EventArgs e)
446                 {
447                         EndpointInputBox eib = new EndpointInputBox();
448
449                         if (eib.ShowDialog(this) == DialogResult.Cancel)
450                                 return;
451
452                         ListViewItem lvi = new ListViewItem();
453                         lvi.Text = eib.txtInstanceName.Text;
454
455                         if (eib.chkConnect.Checked) {
456                                 lvi.SubItems.Add(eib.txtHost.Text);
457                                 lvi.SubItems.Add(eib.txtPort.Text);
458                         }
459
460                         lvwEndpoints.Items.Add(lvi);
461                 }
462
463                 private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
464                 {
465                         btnRemoveEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
466                         btnEditEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
467                 }
468
469                 private void lvwX509Fields_SelectedIndexChanged(object sender, EventArgs e)
470                 {
471                         if (lvwX509Fields.SelectedItems.Count == 0)
472                                 return;
473
474                         ListViewItem lvi = lvwX509Fields.SelectedItems[0];
475
476                         txtX509Field.Text = Convert.ToString(lvi.Tag);
477                 }
478
479                 private void btnRemoveEndpoint_Click(object sender, EventArgs e)
480                 {
481                         while (lvwEndpoints.SelectedItems.Count > 0) {
482                                 lvwEndpoints.Items.Remove(lvwEndpoints.SelectedItems[0]);
483                         }
484                 }
485
486                 private void chkRunServiceAsThisUser_CheckedChanged(object sender, EventArgs e)
487                 {
488                         txtUser.Enabled = !txtUser.Enabled;
489                         if (!txtUser.Enabled)
490                                 txtUser.Text = Icinga2User;
491                 }
492
493                 private void btnEditEndpoint_Click(object sender, EventArgs e)
494                 {
495                         ListViewItem lvi = lvwEndpoints.SelectedItems[0];
496                         EndpointInputBox eib = new EndpointInputBox();
497
498                         eib.Text = "Edit Endpoint";
499                         eib.txtInstanceName.Text = lvi.SubItems[0].Text;
500
501                         if (lvi.SubItems.Count >= 2) {
502                                 eib.txtHost.Text = lvi.SubItems[1].Text;
503                                 eib.txtPort.Text = lvi.SubItems[2].Text;
504                                 eib.chkConnect.Checked = true;
505                         }
506
507                         if (eib.ShowDialog(this) == DialogResult.Cancel)
508                                 return;
509
510                         lvwEndpoints.Items.Remove(lvi);
511
512                         ListViewItem lvi2 = new ListViewItem();
513                         lvi2.Text = eib.txtInstanceName.Text;
514
515                         if (eib.chkConnect.Checked) {
516                                 lvi2.SubItems.Add(eib.txtHost.Text);
517                                 lvi2.SubItems.Add(eib.txtPort.Text);
518                         }
519
520                         lvwEndpoints.Items.Add(lvi2);
521                 }
522         }
523 }
524