]> granicus.if.org Git - icinga2/blob - agent/windows-setup-agent/SetupWizard.cs
f100cc64de9f117219171b751f7ea6f83f381761
[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.Icinga2DataDir + 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.Icinga2DataDir + "\\etc\\icinga2\\pki\\" + txtInstanceName.Text;
148                         string processArguments = "pki new-cert --cn \"" + txtInstanceName.Text + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\"";
149                         string output;
150
151                         if (!File.Exists(pathPrefix + ".crt")) {
152                                 if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
153                                         processArguments,
154                                         out output)) {
155                                         ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
156                                         return;
157                                 }
158                         }
159
160                         SetRetrievalStatus(50);
161
162                         _TrustedFile = Path.GetTempFileName();
163
164                         processArguments = "pki save-cert --host \"" + host + "\" --port \"" + port + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\" --trustedcert \"" + _TrustedFile + "\"";
165                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
166                                 processArguments,
167                                 out output)) {
168                                 ShowErrorText("Running command 'icinga2.exe " + processArguments + "' produced the following output:\n" + output);
169                                 return;
170                         }
171
172                         SetRetrievalStatus(100);
173
174                         X509Certificate2 cert = new X509Certificate2(_TrustedFile);
175                         Invoke((MethodInvoker)delegate { ShowCertificatePrompt(cert); });
176                 }
177
178                 private void ConfigureService()
179                 {
180                         SetConfigureStatus(0, "Updating configuration files...");
181
182                         string output;
183
184                         string args = "";
185
186                         if (rdoNewMaster.Checked)
187                                 args += " --master";
188
189                         Invoke((MethodInvoker)delegate {
190                                 string master_host, master_port;
191                                 GetMasterHostPort(out master_host, out master_port);
192
193                                 args += " --master_host " + master_host + "," + master_port;
194
195                                 foreach (ListViewItem lvi in lvwEndpoints.Items) {
196                                         args += " --endpoint " + lvi.SubItems[0].Text;
197                                         
198                                         if (lvi.SubItems.Count > 1)
199                                                 args += "," + lvi.SubItems[1].Text + "," + lvi.SubItems[2].Text;
200                                 }
201                         });
202
203                         if (rdoListener.Checked)
204                                 args += " --listen ::," + txtListenerPort.Text;
205
206                         if (chkAcceptConfig.Checked)
207                                 args += " --accept-config";
208
209                         if (chkAcceptCommands.Checked)
210                                 args += " --accept-commands";
211
212                         args += " --ticket \"" + txtTicket.Text + "\"";
213                         args += " --trustedcert \"" + _TrustedFile + "\"";
214                         args += " --cn \"" + txtInstanceName.Text + "\"";
215                         args += " --zone \"" + txtInstanceName.Text + "\"";
216
217                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
218                                 "node setup" + args,
219                                 out output)) {
220                                 ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
221                                 return;
222                         }
223
224                         SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
225                         DirectoryInfo di = new DirectoryInfo(Program.Icinga2InstallDir);
226                         DirectorySecurity ds = di.GetAccessControl();
227                         FileSystemAccessRule rule = new FileSystemAccessRule("NT AUTHORITY\\NetworkService",
228                                 FileSystemRights.Modify,
229                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
230                         ds.AddAccessRule(rule);
231                         di.SetAccessControl(ds);
232
233                         SetConfigureStatus(75, "Installing the Icinga 2 service...");
234
235                         RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
236                                 "--scm-uninstall",
237                                 out output);
238
239                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
240                                 "daemon --validate",
241                                 out output)) {
242                                 ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
243                                 return;
244                         }
245
246                         if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
247                                 "--scm-install daemon",
248                                 out output)) {
249                                 ShowErrorText("Running command 'icinga2.exe daemon --scm-install daemon' produced the following output:\n" + output);
250                                 return;
251                         }
252
253                         if (chkInstallNSCP.Checked)
254                         {
255                                 SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");
256
257                                 Process proc = new Process();
258                                 proc.StartInfo.FileName = "msiexec.exe";
259                                 proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP.msi\"";
260                                 proc.Start();
261                                 proc.WaitForExit();
262                         }
263
264                         SetConfigureStatus(100, "Finished.");
265
266                         FinishConfigure();
267                 }
268
269                 private void FinishConfigure()
270                 {
271                         if (InvokeRequired) {
272                                 Invoke((MethodInvoker)FinishConfigure);
273                                 return;
274                         }
275
276                         tbcPages.SelectedTab = tabFinish;
277                 }
278
279                 private void btnBack_Click(object sender, EventArgs e)
280                 {
281                         if (tbcPages.SelectedTab == tabError) {
282                                 tbcPages.SelectedIndex = 0;
283                                 return;
284                         }
285
286                         int offset = 1;
287
288                         if (tbcPages.SelectedTab == tabVerifyCertificate)
289                                 offset++;
290
291                         tbcPages.SelectedIndex -= offset;
292                 }
293
294                 private void btnNext_Click(object sender, EventArgs e)
295                 {
296                         if (tbcPages.SelectedTab == tabParameters) {
297                                 if (txtInstanceName.Text.Length == 0) {
298                                         Warning("Please enter an instance name.");
299                                         return;
300                                 }
301
302                                 if (txtTicket.Text.Length == 0) {
303                                         Warning("Please enter an agent ticket.");
304                                         return;
305                                 }
306
307                                 if (rdoNoMaster.Checked) {
308                                         if (lvwEndpoints.Items.Count == 0) {
309                                                 Warning("You need to add at least one master endpoint.");
310                                                 return;
311                                         }
312
313                                         string host, port;
314                                         if (!GetMasterHostPort(out host, out port)) {
315                                                 Warning("Please enter a remote host and port for at least one of your endpoints.");
316                                                 return;
317                                         }
318                                 }
319
320                                 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
321                                         Warning("You need to specify a listener port.");
322                                         return;
323                                 }
324                         }
325
326                         if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
327                                 Application.Exit();
328
329                         tbcPages.SelectedIndex++;
330                 }
331
332                 private void btnCancel_Click(object sender, EventArgs e)
333                 {
334                         Application.Exit();
335                 }
336
337                 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
338                 {
339                         Refresh();
340
341                         btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
342                         btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
343
344                         if (tbcPages.SelectedTab == tabFinish) {
345                                 btnNext.Text = "&Finish >";
346                                 btnCancel.Enabled = false;
347                         }
348
349                         if (tbcPages.SelectedTab == tabRetrieveCertificate) {
350                                 ListViewItem lvi = lvwEndpoints.Items[0];
351
352                                 string master_host, master_port;
353                                 GetMasterHostPort(out master_host, out master_port);
354
355                                 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
356                                 thread.Start();
357                         }
358
359             /*if (tbcPages.SelectedTab == tabParameters &&
360                                 !File.Exists(Icinga2DataDir + "\\etc\\icinga2\\pki\\agent\\agent.crt")) {
361                                 byte[] bytes = Convert.FromBase64String(txtBundle.Text);
362                                 MemoryStream ms = new MemoryStream(bytes);
363                                 GZipStream gz = new GZipStream(ms, CompressionMode.Decompress);
364                                 MemoryStream ms2 = new MemoryStream();
365
366                                 byte[] buffer = new byte[512];
367                                 int rc;
368                                 while ((rc = gz.Read(buffer, 0, buffer.Length)) > 0)
369                                         ms2.Write(buffer, 0, rc);
370                                 ms2.Position = 0;
371                                 TarReader tr = new TarReader(ms2);
372                                 tr.ReadToEnd(Icinga2DataDir + "\\etc\\icinga2\\pki\\agent");
373                         }*/
374
375             if (tbcPages.SelectedTab == tabConfigure) {
376                                 Thread thread = new Thread(ConfigureService);
377                                 thread.Start();
378                         }
379                 }
380
381                 private void RadioMaster_CheckedChanged(object sender, EventArgs e)
382                 {
383                         lvwEndpoints.Enabled = !rdoNewMaster.Checked;
384                         btnAddEndpoint.Enabled = !rdoNewMaster.Checked;
385                         btnRemoveEndpoint.Enabled = !rdoNewMaster.Checked && lvwEndpoints.SelectedItems.Count > 0;
386                 }
387
388                 private void RadioListener_CheckedChanged(object sender, EventArgs e)
389                 {
390                         txtListenerPort.Enabled = rdoListener.Checked;
391                 }
392
393                 private void AddCertificateField(string name, string shortValue, string longValue = null)
394                 {
395                         ListViewItem lvi = new ListViewItem();
396                         lvi.Text = name;
397                         lvi.SubItems.Add(shortValue);
398                         if (longValue == null)
399                                 longValue = shortValue;
400                         lvi.Tag = longValue;
401                         lvwX509Fields.Items.Add(lvi);
402                 }
403
404                 private string PadText(string input)
405                 {
406                         string output = "";
407
408                         for (int i = 0; i < input.Length; i += 2) {
409                                 if (output != "")
410                                         output += " ";
411
412                                 int len = 2;
413                                 if (input.Length - i < 2)
414                                         len = input.Length - i;
415                                 output += input.Substring(i, len);
416                         }
417
418                         return output;
419                 }
420
421                 private void ShowCertificatePrompt(X509Certificate2 certificate)
422                 {
423                         txtX509Issuer.Text = certificate.Issuer;
424                         txtX509Subject.Text = certificate.Subject;
425
426                         lvwX509Fields.Items.Clear();
427
428                         AddCertificateField("Version", "V" + certificate.Version.ToString());
429                         AddCertificateField("Serial number", certificate.SerialNumber);
430                         AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
431                         AddCertificateField("Valid from", certificate.NotBefore.ToString());
432                         AddCertificateField("Valid to", certificate.NotAfter.ToString());
433
434                         string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
435                         AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);
436
437                         string thumbprint = PadText(certificate.Thumbprint);
438                         AddCertificateField("Thumbprint", thumbprint);
439
440                         tbcPages.SelectedTab = tabVerifyCertificate;
441                 }
442
443                 private void btnAddEndpoint_Click(object sender, EventArgs e)
444                 {
445                         EndpointInputBox eib = new EndpointInputBox();
446
447                         if (eib.ShowDialog(this) == DialogResult.Cancel)
448                                 return;
449
450                         ListViewItem lvi = new ListViewItem();
451                         lvi.Text = eib.txtInstanceName.Text;
452
453                         if (eib.chkConnect.Checked) {
454                                 lvi.SubItems.Add(eib.txtHost.Text);
455                                 lvi.SubItems.Add(eib.txtPort.Text);
456                         }
457
458                         lvwEndpoints.Items.Add(lvi);
459                 }
460
461                 private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
462                 {
463                         btnRemoveEndpoint.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 = (string)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 }