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 Microsoft.Win32;
12 using System.IO.Compression;
13 using System.Diagnostics;
14 using System.ServiceProcess;
15 using System.Security.AccessControl;
19 public partial class SetupWizard : Form
21 private string _TrustedFile;
25 InitializeComponent();
27 txtInstanceName.Text = Icinga2InstanceName;
30 private void FatalError(string message)
32 MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
36 private void Warning(string message)
38 MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
41 private string Icinga2InstallDir
45 RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Icinga Development Team\\ICINGA2");
50 return (string)rk.GetValue("");
54 private string Icinga2InstanceName
58 IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties();
60 string fqdn = props.HostName;
62 if (props.DomainName != "")
63 fqdn += "." + props.DomainName;
69 private bool GetMasterHostPort(out string host, out string port)
71 foreach (ListViewItem lvi in lvwEndpoints.Items) {
72 if (lvi.SubItems.Count > 1) {
73 host = lvi.SubItems[1].Text;
74 port = lvi.SubItems[2].Text;
84 private void EnableFeature(string feature)
88 fp = File.Open(Icinga2InstallDir + String.Format("\\etc\\icinga2\\features-enabled\\{0}.conf", feature), FileMode.Create);
89 using (StreamWriter sw = new StreamWriter(fp, Encoding.ASCII)) {
91 sw.Write(String.Format("include \"../features-available/{0}.conf\"\n", feature));
99 private void SetRetrievalStatus(int pct)
101 if (InvokeRequired) {
102 Invoke((MethodInvoker)delegate { SetRetrievalStatus(pct); });
106 prgRetrieveCertificate.Value = pct;
109 private void SetConfigureStatus(int pct, string message)
111 if (InvokeRequired) {
112 Invoke((MethodInvoker)delegate { SetConfigureStatus(pct, message); });
116 prgConfig.Value = pct;
117 lblConfigStatus.Text = message;
120 private void ShowErrorText(string text)
122 if (InvokeRequired) {
123 Invoke((MethodInvoker)delegate { ShowErrorText(text); });
127 txtError.Text = text;
128 tbcPages.SelectedTab = tabError;
131 private bool RunProcess(string filename, string arguments, out string output)
133 ProcessStartInfo psi = new ProcessStartInfo();
134 psi.FileName = filename;
135 psi.Arguments = arguments;
136 psi.CreateNoWindow = true;
137 psi.UseShellExecute = false;
138 psi.RedirectStandardOutput = true;
139 psi.RedirectStandardError = true;
143 using (Process proc = Process.Start(psi)) {
144 proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args) {
145 result += args.Data + "\r\n";
147 proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args) {
148 result += args.Data + "\r\n";
150 proc.BeginOutputReadLine();
151 proc.BeginErrorReadLine();
156 if (proc.ExitCode != 0)
163 private void VerifyCertificate(string host, string port)
165 SetRetrievalStatus(25);
167 string pathPrefix = Icinga2InstallDir + "\\etc\\icinga2\\pki\\" + txtInstanceName.Text;
171 if (!File.Exists(pathPrefix + ".crt")) {
172 if (!RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
173 "pki new-cert --cn \"" + txtInstanceName.Text + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\"",
175 ShowErrorText(output);
180 SetRetrievalStatus(50);
182 _TrustedFile = Path.GetTempFileName();
184 if (!RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
185 "pki save-cert --host \"" + host + "\" --port \"" + port + "\" --key \"" + pathPrefix + ".key\" --cert \"" + pathPrefix + ".crt\" --trustedcert \"" + _TrustedFile + "\"",
187 ShowErrorText(output);
191 SetRetrievalStatus(100);
193 X509Certificate2 cert = new X509Certificate2(_TrustedFile);
194 Invoke((MethodInvoker)delegate { ShowCertificatePrompt(cert); });
197 private void ConfigureService()
199 SetConfigureStatus(0, "Updating configuration files...");
205 if (rdoNewMaster.Checked)
208 Invoke((MethodInvoker)delegate {
209 string master_host, master_port;
210 GetMasterHostPort(out master_host, out master_port);
212 args += " --master_host " + master_host + "," + master_port;
214 foreach (ListViewItem lvi in lvwEndpoints.Items) {
215 args += " --endpoint " + lvi.SubItems[0].Text;
217 if (lvi.SubItems.Count > 1)
218 args += "," + lvi.SubItems[1].Text + "," + lvi.SubItems[2].Text;
222 if (rdoListener.Checked)
223 args += " --listen ::," + txtListenerPort.Text;
225 args += " --ticket " + txtTicket.Text;
226 args += " --trustedcert " + _TrustedFile;
227 args += " --cn " + txtInstanceName.Text;
228 args += " --zone " + txtInstanceName.Text;
230 if (!RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
233 ShowErrorText(output);
237 SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
238 DirectoryInfo di = new DirectoryInfo(Icinga2InstallDir);
239 DirectorySecurity ds = di.GetAccessControl();
240 FileSystemAccessRule rule = new FileSystemAccessRule("NT AUTHORITY\\NetworkService",
241 FileSystemRights.Modify,
242 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
243 ds.AddAccessRule(rule);
244 di.SetAccessControl(ds);
246 SetConfigureStatus(75, "Installing the Icinga 2 service...");
248 RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
252 if (!RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
255 ShowErrorText(output);
259 if (!RunProcess(Icinga2InstallDir + "\\sbin\\icinga2.exe",
260 "--scm-install daemon",
262 ShowErrorText(output);
266 SetConfigureStatus(100, "Finished.");
271 private void FinishConfigure()
273 if (InvokeRequired) {
274 Invoke((MethodInvoker)FinishConfigure);
278 tbcPages.SelectedTab = tabFinish;
281 private void AgentWizard_Shown(object sender, EventArgs e)
283 string installDir = Icinga2InstallDir;
285 if (installDir == "")
286 FatalError("Icinga 2 does not seem to be installed properly.");
288 /* TODO: This is something the NSIS installer should do */
289 Directory.CreateDirectory(installDir + "\\etc\\icinga2\\pki");
290 Directory.CreateDirectory(installDir + "\\var\\cache\\icinga2");
291 Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\pki");
292 Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\agent\\inventory");
293 Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\config");
294 Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\log");
295 Directory.CreateDirectory(installDir + "\\var\\lib\\icinga2\\api\\zones");
296 Directory.CreateDirectory(installDir + "\\var\\log\\icinga2\\compat\\archive");
297 Directory.CreateDirectory(installDir + "\\var\\log\\icinga2\\crash");
298 Directory.CreateDirectory(installDir + "\\var\\run\\icinga2\\cmd");
299 Directory.CreateDirectory(installDir + "\\var\\spool\\icinga2\\perfdata");
300 Directory.CreateDirectory(installDir + "\\var\\spool\\icinga2\\tmp");
303 private void btnBack_Click(object sender, EventArgs e)
305 if (tbcPages.SelectedTab == tabError) {
306 tbcPages.SelectedIndex = 0;
312 if (tbcPages.SelectedTab == tabVerifyCertificate)
315 tbcPages.SelectedIndex -= offset;
318 private void btnNext_Click(object sender, EventArgs e)
320 if (tbcPages.SelectedTab == tabParameters) {
321 if (txtInstanceName.Text.Length == 0) {
322 Warning("Please enter an instance name.");
326 if (txtTicket.Text.Length == 0) {
327 Warning("Please enter an agent ticket.");
331 if (rdoNoMaster.Checked) {
332 if (lvwEndpoints.Items.Count == 0) {
333 Warning("You need to add at least one master endpoint.");
338 if (!GetMasterHostPort(out host, out port)) {
339 Warning("Please enter a remote host and port for at least one of your endpoints.");
344 if (rdoListener.Checked && (txtListenerPort.Text == "")) {
345 Warning("You need to specify a listener port.");
350 if (tbcPages.SelectedTab == tabFinish || tbcPages.SelectedTab == tabError)
353 tbcPages.SelectedIndex++;
356 private void btnCancel_Click(object sender, EventArgs e)
361 private void tbcPages_SelectedIndexChanged(object sender, EventArgs e)
365 btnBack.Enabled = (tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabError);
366 btnNext.Enabled = (tbcPages.SelectedTab == tabParameters || tbcPages.SelectedTab == tabVerifyCertificate || tbcPages.SelectedTab == tabFinish);
368 if (tbcPages.SelectedTab == tabFinish) {
369 btnNext.Text = "&Finish >";
370 btnCancel.Enabled = false;
373 if (tbcPages.SelectedTab == tabRetrieveCertificate) {
374 ListViewItem lvi = lvwEndpoints.Items[0];
376 string master_host, master_port;
377 GetMasterHostPort(out master_host, out master_port);
379 Thread thread = new Thread((ThreadStart)delegate { VerifyCertificate(master_host, master_port); });
383 /*if (tbcPages.SelectedTab == tabParameters &&
384 !File.Exists(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent\\agent.crt")) {
385 byte[] bytes = Convert.FromBase64String(txtBundle.Text);
386 MemoryStream ms = new MemoryStream(bytes);
387 GZipStream gz = new GZipStream(ms, CompressionMode.Decompress);
388 MemoryStream ms2 = new MemoryStream();
390 byte[] buffer = new byte[512];
392 while ((rc = gz.Read(buffer, 0, buffer.Length)) > 0)
393 ms2.Write(buffer, 0, rc);
395 TarReader tr = new TarReader(ms2);
396 tr.ReadToEnd(Icinga2InstallDir + "\\etc\\icinga2\\pki\\agent");
399 if (tbcPages.SelectedTab == tabConfigure) {
400 Thread thread = new Thread(ConfigureService);
405 private void RadioMaster_CheckedChanged(object sender, EventArgs e)
407 lvwEndpoints.Enabled = !rdoNewMaster.Checked;
408 btnAddEndpoint.Enabled = !rdoNewMaster.Checked;
409 btnRemoveEndpoint.Enabled = !rdoNewMaster.Checked && lvwEndpoints.SelectedItems.Count > 0;
412 private void RadioListener_CheckedChanged(object sender, EventArgs e)
414 txtListenerPort.Enabled = rdoListener.Checked;
417 private void AddCertificateField(string name, string shortValue, string longValue = null)
419 ListViewItem lvi = new ListViewItem();
421 lvi.SubItems.Add(shortValue);
422 if (longValue == null)
423 longValue = shortValue;
425 lvwX509Fields.Items.Add(lvi);
428 private string PadText(string input)
432 for (int i = 0; i < input.Length; i += 2) {
437 if (input.Length - i < 2)
438 len = input.Length - i;
439 output += input.Substring(i, len);
445 private void ShowCertificatePrompt(X509Certificate2 certificate)
447 txtX509Issuer.Text = certificate.Issuer;
448 txtX509Subject.Text = certificate.Subject;
450 lvwX509Fields.Items.Clear();
452 AddCertificateField("Version", "V" + certificate.Version.ToString());
453 AddCertificateField("Serial number", certificate.SerialNumber);
454 AddCertificateField("Signature algorithm", certificate.SignatureAlgorithm.FriendlyName);
455 AddCertificateField("Valid from", certificate.NotBefore.ToString());
456 AddCertificateField("Valid to", certificate.NotAfter.ToString());
458 string pkey = BitConverter.ToString(certificate.PublicKey.EncodedKeyValue.RawData).Replace("-", " ");
459 AddCertificateField("Public key", certificate.PublicKey.Oid.FriendlyName + " (" + certificate.PublicKey.Key.KeySize + " bits)", pkey);
461 string thumbprint = PadText(certificate.Thumbprint);
462 AddCertificateField("Thumbprint", thumbprint);
464 tbcPages.SelectedTab = tabVerifyCertificate;
467 private void btnAddEndpoint_Click(object sender, EventArgs e)
469 EndpointInputBox eib = new EndpointInputBox();
471 if (eib.ShowDialog(this) == DialogResult.Cancel)
474 ListViewItem lvi = new ListViewItem();
475 lvi.Text = eib.txtInstanceName.Text;
477 if (eib.chkConnect.Checked) {
478 lvi.SubItems.Add(eib.txtHost.Text);
479 lvi.SubItems.Add(eib.txtPort.Text);
482 lvwEndpoints.Items.Add(lvi);
485 private void lvwEndpoints_SelectedIndexChanged(object sender, EventArgs e)
487 btnRemoveEndpoint.Enabled = lvwEndpoints.SelectedItems.Count > 0;
490 private void lvwX509Fields_SelectedIndexChanged(object sender, EventArgs e)
492 if (lvwX509Fields.SelectedItems.Count == 0)
495 ListViewItem lvi = lvwX509Fields.SelectedItems[0];
497 txtX509Field.Text = (string)lvi.Tag;
500 private void btnRemoveEndpoint_Click(object sender, EventArgs e)
502 while (lvwEndpoints.SelectedItems.Count > 0) {
503 lvwEndpoints.Items.Remove(lvwEndpoints.SelectedItems[0]);