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