]> granicus.if.org Git - icinga2/blob - agent/windows-setup-agent/SetupWizard.cs
Remove unused code in the Windows wizard
[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.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 btnBack_Click(object sender, EventArgs e)
279                 {
280                         if (tbcPages.SelectedTab == tabError) {
281                                 tbcPages.SelectedIndex = 0;
282                                 return;
283                         }
284
285                         int offset = 1;
286
287                         if (tbcPages.SelectedTab == tabVerifyCertificate)
288                                 offset++;
289
290                         tbcPages.SelectedIndex -= offset;
291                 }
292
293                 private void btnNext_Click(object sender, EventArgs e)
294                 {
295                         if (tbcPages.SelectedTab == tabParameters) {
296                                 if (txtInstanceName.Text.Length == 0) {
297                                         Warning("Please enter an instance name.");
298                                         return;
299                                 }
300
301                                 if (txtTicket.Text.Length == 0) {
302                                         Warning("Please enter an agent ticket.");
303                                         return;
304                                 }
305
306                                 if (rdoNoMaster.Checked) {
307                                         if (lvwEndpoints.Items.Count == 0) {
308                                                 Warning("You need to add at least one master endpoint.");
309                                                 return;
310                                         }
311
312                                         string host, port;
313                                         if (!GetMasterHostPort(out host, out port)) {
314                                                 Warning("Please enter a remote host and port for at least one of your endpoints.");
315                                                 return;
316                                         }
317                                 }
318
319                                 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
320                                         Warning("You need to specify a listener port.");
321                                         return;
322                                 }
323                         }
324
325                         if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
326                                 Application.Exit();
327
328                         tbcPages.SelectedIndex++;
329                 }
330
331                 private void btnCancel_Click(object sender, EventArgs e)
332                 {
333                         Application.Exit();
334                 }
335
336                 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
337                 {
338                         Refresh();
339
340                         btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
341                         btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
342
343                         if (tbcPages.SelectedTab == tabFinish) {
344                                 btnNext.Text = "&Finish >";
345                                 btnCancel.Enabled = false;
346                         }
347
348                         if (tbcPages.SelectedTab == tabRetrieveCertificate) {
349                                 ListViewItem lvi = lvwEndpoints.Items[0];
350
351                                 string master_host, master_port;
352                                 GetMasterHostPort(out master_host, out master_port);
353
354                                 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
355                                 thread.Start();
356                         }
357
358                         /*if (tbcPages.SelectedTab == tabParameters &&
359                                 !File.Exists(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent\\agent.crt")) {
360                                 byte[] bytes = Convert.FromBase64String(txtBundle.Text);
361                                 MemoryStream ms = new MemoryStream(bytes);
362                                 GZipStream gz = new GZipStream(ms, CompressionMode.Decompress);
363                                 MemoryStream ms2 = new MemoryStream();
364
365                                 byte[] buffer = new byte[512];
366                                 int rc;
367                                 while ((rc = gz.Read(buffer, 0, buffer.Length)) > 0)
368                                         ms2.Write(buffer, 0, rc);
369                                 ms2.Position = 0;
370                                 TarReader tr = new TarReader(ms2);
371                                 tr.ReadToEnd(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent");
372                         }*/
373
374                         if (tbcPages.SelectedTab == tabConfigure) {
375                                 Thread thread = new Thread(ConfigureService);
376                                 thread.Start();
377                         }
378                 }
379
380                 private void RadioMaster_CheckedChanged(object sender, EventArgs e)
381                 {
382                         lvwEndpoints.Enabled = !rdoNewMaster.Checked;
383                         btnAddEndpoint.Enabled = !rdoNewMaster.Checked;
384                         btnRemoveEndpoint.Enabled = !rdoNewMaster.Checked && lvwEndpoints.SelectedItems.Count > 0;
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                 }
464
465                 private void lvwX509Fields_SelectedIndexChanged(object sender, EventArgs e)
466                 {
467                         if (lvwX509Fields.SelectedItems.Count == 0)
468                                 return;
469
470                         ListViewItem lvi = lvwX509Fields.SelectedItems[0];
471
472                         txtX509Field.Text = (string)lvi.Tag;
473                 }
474
475                 private void btnRemoveEndpoint_Click(object sender, EventArgs e)
476                 {
477                         while (lvwEndpoints.SelectedItems.Count > 0) {
478                                 lvwEndpoints.Items.Remove(lvwEndpoints.SelectedItems[0]);
479                         }
480         }
481         }
482 }