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