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