]> granicus.if.org Git - icinga2/blob - agent/windows-setup-agent/SetupWizard.cs
Merge branch 'support/2.3'
[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
22                 public SetupWizard()
23                 {
24                         InitializeComponent();
25
26                         txtInstanceName.Text = Icinga2InstanceName;
27                 }
28
29                 private void Warning(string message)
30                 {
31                         MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
32                 }
33
34                 private string Icinga2InstanceName
35                 {
36                         get
37                         {
38                                 IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties();
39
40                                 string fqdn = props.HostName;
41
42                                 if (props.DomainName != "")
43                                         fqdn += "." + props.DomainName;
44
45                                 return fqdn;
46                         }
47                 }
48
49                 private bool GetMasterHostPort(out string host, out string port)
50                 {
51                         foreach (ListViewItem lvi in lvwEndpoints.Items) {
52                                 if (lvi.SubItems.Count > 1) {
53                                         host = lvi.SubItems[1].Text;
54                                         port = lvi.SubItems[2].Text;
55                                         return true;
56                                 }
57                         }
58
59                         host = null;
60                         port = null;
61                         return false;
62                 }
63
64                 private void EnableFeature(string feature)
65                 {
66                         FileStream fp = null;
67                         try {
68                                 fp = File.Open(Program.Icinga2InstallDir + String.Format("\\etc\\icinga2\\features-enabled\\{0}.conf", feature), FileMode.Create);
69                                 using (StreamWriter sw = new StreamWriter(fp, Encoding.ASCII)) {
70                                         fp = null;
71                                         sw.Write(String.Format("include \"../features-available/{0}.conf\"\n", feature));
72                                 }
73                         } finally {
74                                 if (fp != null)
75                                         fp.Dispose();
76                         }
77                 }
78
79                 private void SetRetrievalStatus(int pct)
80                 {
81                         if (InvokeRequired) {
82                                 Invoke((MethodInvoker)delegate { SetRetrievalStatus(pct); });
83                                 return;
84                         }
85
86                         prgRetrieveCertificate.Value = pct;
87                 }
88
89                 private void SetConfigureStatus(int pct, string message)
90                 {
91                         if (InvokeRequired) {
92                                 Invoke((MethodInvoker)delegate { SetConfigureStatus(pct, message); });
93                                 return;
94                         }
95
96                         prgConfig.Value = pct;
97                         lblConfigStatus.Text = message;
98                 }
99
100                 private void ShowErrorText(string text)
101                 {
102                         if (InvokeRequired) {
103                                 Invoke((MethodInvoker)delegate { ShowErrorText(text); });
104                                 return;
105                         }
106
107                         txtError.Text = text;
108                         tbcPages.SelectedTab = tabError;
109                 }
110
111                 private bool RunProcess(string filename, string arguments, out string output)
112                 {
113                         ProcessStartInfo psi = new ProcessStartInfo();
114                         psi.FileName = filename;
115                         psi.Arguments = arguments;
116                         psi.CreateNoWindow = true;
117                         psi.UseShellExecute = false;
118                         psi.RedirectStandardOutput = true;
119                         psi.RedirectStandardError = true;
120
121                         String result = "";
122
123                         using (Process proc = Process.Start(psi)) {
124                                 proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args) {
125                                         result += args.Data + "\r\n";
126                                 };
127                                 proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args) {
128                                         result += args.Data + "\r\n";
129                                 };
130                                 proc.BeginOutputReadLine();
131                                 proc.BeginErrorReadLine();
132                                 proc.WaitForExit();
133
134                                 output = result;
135
136                                 if (proc.ExitCode != 0)
137                                         return false;
138                         }
139
140                         return true;
141                 }
142
143                 private void VerifyCertificate(string host, string port)
144                 {
145                         SetRetrievalStatus(25);
146
147                         string pathPrefix = Program.Icinga2InstallDir + "\\etc\\icinga2\\pki\\" + txtInstanceName.Text;
148
149                         string output;
150
151                         if (!File.Exists(pathPrefix + ".crt")) {
152                                 if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
153                                         "pki new-cert --cn \"" + txtInstanceName.Text + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\"",
154                                         out output)) {
155                                         ShowErrorText(output);
156                                         return;
157                                 }
158                         }
159
160                         SetRetrievalStatus(50);
161
162                         _TrustedFile = Path.GetTempFileName();
163
164                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
165                                 "pki save-cert --host \"" + host + "\" --port \"" + port + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\" --trustedcert \"" + _TrustedFile + "\"",
166                                 out output)) {
167                                 ShowErrorText(output);
168                                 return;
169                         }
170
171                         SetRetrievalStatus(100);
172
173                         X509Certificate2 cert = new X509Certificate2(_TrustedFile);
174                         Invoke((MethodInvoker)delegate { ShowCertificatePrompt(cert); });
175                 }
176
177                 private void ConfigureService()
178                 {
179                         SetConfigureStatus(0, "Updating configuration files...");
180
181                         string output;
182
183                         string args = "";
184
185                         if (rdoNewMaster.Checked)
186                                 args += " --master";
187
188                         Invoke((MethodInvoker)delegate {
189                                 string master_host, master_port;
190                                 GetMasterHostPort(out master_host, out master_port);
191
192                                 args += " --master_host " + master_host + "," + master_port;
193
194                                 foreach (ListViewItem lvi in lvwEndpoints.Items) {
195                                         args += " --endpoint " + lvi.SubItems[0].Text;
196                                         
197                                         if (lvi.SubItems.Count > 1)
198                                                 args += "," + lvi.SubItems[1].Text + "," + lvi.SubItems[2].Text;
199                                 }
200                         });
201
202                         if (rdoListener.Checked)
203                                 args += " --listen ::," + txtListenerPort.Text;
204
205                         if (chkAcceptConfig.Checked)
206                                 args += " --accept-config";
207
208                         if (chkAcceptCommands.Checked)
209                                 args += " --accept-commands";
210
211                         args += " --ticket " + txtTicket.Text;
212                         args += " --trustedcert " + _TrustedFile;
213                         args += " --cn " + txtInstanceName.Text;
214                         args += " --zone " + txtInstanceName.Text;
215
216                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
217                                 "node setup" + args,
218                                 out output)) {
219                                 ShowErrorText(output);
220                                 return;
221                         }
222
223                         SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
224                         DirectoryInfo di = new DirectoryInfo(Program.Icinga2InstallDir);
225                         DirectorySecurity ds = di.GetAccessControl();
226                         FileSystemAccessRule rule = new FileSystemAccessRule("NT AUTHORITY\\NetworkService",
227                                 FileSystemRights.Modify,
228                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
229                         ds.AddAccessRule(rule);
230                         di.SetAccessControl(ds);
231
232                         SetConfigureStatus(75, "Installing the Icinga 2 service...");
233
234                         RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
235                                 "--scm-uninstall",
236                                 out output);
237
238                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
239                                 "daemon --validate",
240                                 out output)) {
241                                 ShowErrorText(output);
242                                 return;
243                         }
244
245                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
246                                 "--scm-install daemon",
247                                 out output)) {
248                                 ShowErrorText(output);
249                                 return;
250                         }
251
252                         if (chkInstallNSCP.Checked)
253                         {
254                                 SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");
255
256                                 Process proc = new Process();
257                                 proc.StartInfo.FileName = "msiexec.exe";
258                                 proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP-Win32.msi\"";
259                                 proc.Start();
260                                 proc.WaitForExit();
261                         }
262
263                         SetConfigureStatus(100, "Finished.");
264
265                         FinishConfigure();
266                 }
267
268                 private void FinishConfigure()
269                 {
270                         if (InvokeRequired) {
271                                 Invoke((MethodInvoker)FinishConfigure);
272                                 return;
273                         }
274
275                         tbcPages.SelectedTab = tabFinish;
276                 }
277
278                 private void AgentWizard_Shown(object sender, EventArgs e)
279                 {
280                         string installDir = Program.Icinga2InstallDir;
281
282                         /* TODO: This is something the NSIS installer should do */
283                         Directory.CreateDirectory(installDir + "\\etc\\icinga2\\pki");
284                         Directory.CreateDirectory(installDir + "\\var\\cache\\icinga2");
285                         Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\pki");
286                         Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\agent\\inventory");
287                         Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\config");
288                         Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\log");
289                         Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\zones");
290                         Directory.CreateDirectory(installDir + "\\var\\log\\icinga2\\compat\\archive");
291                         Directory.CreateDirectory(installDir + "\\var\\log\\icinga2\\crash");
292                         Directory.CreateDirectory(installDir + "\\var\\run\\icinga2\\cmd");
293                         Directory.CreateDirectory(installDir + "\\var\\spool\\icinga2\\perfdata");
294                         Directory.CreateDirectory(installDir + "\\var\\spool\\icinga2\\tmp");
295                 }
296
297                 private void btnBack_Click(object sender, EventArgs e)
298                 {
299                         if (tbcPages.SelectedTab == tabError) {
300                                 tbcPages.SelectedIndex = 0;
301                                 return;
302                         }
303
304                         int offset = 1;
305
306                         if (tbcPages.SelectedTab == tabVerifyCertificate)
307                                 offset++;
308
309                         tbcPages.SelectedIndex -= offset;
310                 }
311
312                 private void btnNext_Click(object sender, EventArgs e)
313                 {
314                         if (tbcPages.SelectedTab == tabParameters) {
315                                 if (txtInstanceName.Text.Length == 0) {
316                                         Warning("Please enter an instance name.");
317                                         return;
318                                 }
319
320                                 if (txtTicket.Text.Length == 0) {
321                                         Warning("Please enter an agent ticket.");
322                                         return;
323                                 }
324
325                                 if (rdoNoMaster.Checked) {
326                                         if (lvwEndpoints.Items.Count == 0) {
327                                                 Warning("You need to add at least one master 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
338                                 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
339                                         Warning("You need to specify a listener port.");
340                                         return;
341                                 }
342                         }
343
344                         if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
345                                 Application.Exit();
346
347                         tbcPages.SelectedIndex++;
348                 }
349
350                 private void btnCancel_Click(object sender, EventArgs e)
351                 {
352                         Application.Exit();
353                 }
354
355                 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
356                 {
357                         Refresh();
358
359                         btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
360                         btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
361
362                         if (tbcPages.SelectedTab == tabFinish) {
363                                 btnNext.Text = "&Finish >";
364                                 btnCancel.Enabled = false;
365                         }
366
367                         if (tbcPages.SelectedTab == tabRetrieveCertificate) {
368                                 ListViewItem lvi = lvwEndpoints.Items[0];
369
370                                 string master_host, master_port;
371                                 GetMasterHostPort(out master_host, out master_port);
372
373                                 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
374                                 thread.Start();
375                         }
376
377                         /*if (tbcPages.SelectedTab == tabParameters &&
378                                 !File.Exists(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent\\agent.crt")) {
379                                 byte[] bytes = Convert.FromBase64String(txtBundle.Text);
380                                 MemoryStream ms = new MemoryStream(bytes);
381                                 GZipStream gz = new GZipStream(ms, CompressionMode.Decompress);
382                                 MemoryStream ms2 = new MemoryStream();
383
384                                 byte[] buffer = new byte[512];
385                                 int rc;
386                                 while ((rc = gz.Read(buffer, 0, buffer.Length)) > 0)
387                                         ms2.Write(buffer, 0, rc);
388                                 ms2.Position = 0;
389                                 TarReader tr = new TarReader(ms2);
390                                 tr.ReadToEnd(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent");
391                         }*/
392
393                         if (tbcPages.SelectedTab == tabConfigure) {
394                                 Thread thread = new Thread(ConfigureService);
395                                 thread.Start();
396                         }
397                 }
398
399                 private void RadioMaster_CheckedChanged(object sender, EventArgs e)
400                 {
401                         lvwEndpoints.Enabled = !rdoNewMaster.Checked;
402                         btnAddEndpoint.Enabled = !rdoNewMaster.Checked;
403                         btnRemoveEndpoint.Enabled = !rdoNewMaster.Checked && lvwEndpoints.SelectedItems.Count > 0;
404                 }
405
406                 private void RadioListener_CheckedChanged(object sender, EventArgs e)
407                 {
408                         txtListenerPort.Enabled = rdoListener.Checked;
409                 }
410
411                 private void AddCertificateField(string name, string shortValue, string longValue = null)
412                 {
413                         ListViewItem lvi = new ListViewItem();
414                         lvi.Text = name;
415                         lvi.SubItems.Add(shortValue);
416                         if (longValue == null)
417                                 longValue = shortValue;
418                         lvi.Tag = longValue;
419                         lvwX509Fields.Items.Add(lvi);
420                 }
421
422                 private string PadText(string input)
423                 {
424                         string output = "";
425
426                         for (int i = 0; i < input.Length; i += 2) {
427                                 if (output != "")
428                                         output += " ";
429
430                                 int len = 2;
431                                 if (input.Length - i < 2)
432                                         len = input.Length - i;
433                                 output += input.Substring(i, len);
434                         }
435
436                         return output;
437                 }
438
439                 private void ShowCertificatePrompt(X509Certificate2 certificate)
440                 {
441                         txtX509Issuer.Text = certificate.Issuer;
442                         txtX509Subject.Text = certificate.Subject;
443
444                         lvwX509Fields.Items.Clear();
445
446                         AddCertificateField("Version", "V" + certificate.Version.ToString());
447                         AddCertificateField("Serial number", certificate.SerialNumber);
448                         AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
449                         AddCertificateField("Valid from", certificate.NotBefore.ToString());
450                         AddCertificateField("Valid to", certificate.NotAfter.ToString());
451
452                         string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
453                         AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);
454
455                         string thumbprint = PadText(certificate.Thumbprint);
456                         AddCertificateField("Thumbprint", thumbprint);
457
458                         tbcPages.SelectedTab = tabVerifyCertificate;
459                 }
460
461                 private void btnAddEndpoint_Click(object sender, EventArgs e)
462                 {
463                         EndpointInputBox eib = new EndpointInputBox();
464
465                         if (eib.ShowDialog(this) == DialogResult.Cancel)
466                                 return;
467
468                         ListViewItem lvi = new ListViewItem();
469                         lvi.Text = eib.txtInstanceName.Text;
470
471                         if (eib.chkConnect.Checked) {
472                                 lvi.SubItems.Add(eib.txtHost.Text);
473                                 lvi.SubItems.Add(eib.txtPort.Text);
474                         }
475
476                         lvwEndpoints.Items.Add(lvi);
477                 }
478
479                 private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
480                 {
481                         btnRemoveEndpoint.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 }