Exemplo n.º 1
0
        public async System.Threading.Tasks.Task <dynamic> SendAsync(INatDevice Router, string ApiKey, string Key)
        {
            try
            {
                this.ExternalIP = Router.GetExternalIP().ToString();
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.Message);
                this.ExternalIP = "";
            }

            string Hostname = Dns.GetHostName();

            this.IsPortMapped = StaticHelpers.isPortMappedOnRouter(Router);

            ManagementObject os     = new ManagementObject("Win32_OperatingSystem=@");
            string           serial = (string)os["SerialNumber"];

            var values = new Dictionary <string, string>
            {
                { "status", IsPortMapped ? "open" : "closed" },
                { "rdpopen", StaticHelpers.isRDPAvailable() ? "1" : "0" },
                { "wanip", this.ExternalIP != null ? this.ExternalIP : "" },
                { "lanip", StaticHelpers.GetInternalIP() },
                { "port", Registry.Get("Port") },
                { "host", Hostname },
                { "interval", Registry.Get("Interval") },
                { "lifetime", Registry.Get("PortLifetime") },
                { "version", StaticHelpers.GetVersion() },
                { "guid", serial },
                { "serviceinstalled", StaticHelpers.IsServiceInstalled().ToString() },
                { "servicerunning", StaticHelpers.IsServiceRunning().ToString() }
            };

            var serializer = new JavaScriptSerializer();

            var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "hostid", StaticHelpers.GetHostHash(Hostname) },
                { "apikey", ApiKey },
                { "payload", Harpocrates.Engine.Encrypt(serializer.Serialize(values), Key) }
            });

            // HttpWebRequest request = WebRequest.Create(Endpoint) as HttpWebRequest;
            // request.Proxy = new WebProxy(MyProxyHostString, MyProxyPort);

            // Send the API call
            HttpClient client   = new HttpClient();
            dynamic    response = await client.PostAsync(Endpoint, content);

            // Parse out the account TTL header
            IEnumerable <string> ttls;

            if (response.Headers.TryGetValues("ttl", out ttls))
            {
                foreach (string ttl in ttls)
                {
                    this.LifeTime = Int32.Parse(ttl);
                }
            }

            // Parse out version header
            IEnumerable <string> versions;

            if (response.Headers.TryGetValues("version", out versions))
            {
                foreach (string version in versions)
                {
                    this.Version = version;
                }
            }

            this.CommandWasProcessed = ProcessCommandHeader(Router, response, Key);

            // Create the machines List
            string responseString = await response.Content.ReadAsStringAsync();

            List <Dictionary <string, string> > RemoteMachinesRaw = new JavaScriptSerializer().Deserialize <List <Dictionary <string, string> > >(responseString);

            // If there was some error parsing the json, just quit here...
            if (RemoteMachinesRaw == null)
            {
                return(response);
            }

            foreach (var a in RemoteMachinesRaw)
            {
                RemoteMachineImportJson parsed;

                // First try to decrypt one return parameter for this machine
                // If decryption fails then other machine probably has different key
                try
                {
                    string payloadDecrypted = Harpocrates.Engine.Decrypt(a["payload"], Key);
                    parsed = serializer.Deserialize <RemoteMachineImportJson>(payloadDecrypted);
                }
                catch
                {
                    continue;
                }

                RemoteMachine x = new RemoteMachine();

                x.wanip            = parsed.wanip;
                x.lanip            = parsed.lanip;
                x.host             = parsed.host;
                x.port             = Int32.Parse(parsed.port);
                x.pending          = Convert.ToBoolean(Convert.ToInt32(a["pending"]));
                x.rdpopen          = Convert.ToBoolean(Convert.ToInt32(parsed.rdpopen));
                x.status           = parsed.status;
                x.version          = parsed.version;
                x.interval         = Int32.Parse(parsed.interval);
                x.lifetime         = Int32.Parse(parsed.lifetime);
                x.guid             = parsed.guid;
                x.servicerunning   = Boolean.Parse(parsed.servicerunning);
                x.serviceinstalled = Boolean.Parse(parsed.serviceinstalled);

                RemoteMachines.Add(x.host, x);
            }

            return(response);
        }
Exemplo n.º 2
0
        public void RefreshWindowsServiceMenu()
        {
            // Delete all of the existing items
            while (this.WindowsServiceMenuItem.DropDownItems.Count > 0)
            {
                this.WindowsServiceMenuItem.DropDownItems.RemoveAt(0);
            }

            Font f = new Font("Consolas", 9);

            ToolStripLabel WindowsServiceInstalledLabelItem = new ToolStripLabel();

            WindowsServiceInstalledLabelItem.Text = "Installation Status: " + (StaticHelpers.IsServiceInstalled() ? "Installed" : "Not Installed!");
            WindowsServiceInstalledLabelItem.Font = f;
            if (StaticHelpers.IsServiceInstalled() == true)
            {
                WindowsServiceInstalledLabelItem.Image = Properties.Resources.bullet_green;
            }
            else
            {
                WindowsServiceInstalledLabelItem.Image = Properties.Resources.bullet_yellow;
            }
            WindowsServiceMenuItem.DropDownItems.Add(WindowsServiceInstalledLabelItem);

            ToolStripLabel WindowsServiceStatusLabelItem = new ToolStripLabel();

            WindowsServiceStatusLabelItem.Text = "Operational Status : " + (StaticHelpers.IsServiceRunning() ? "Running" : "Not Running!");
            WindowsServiceStatusLabelItem.Font = f;
            if (StaticHelpers.IsServiceRunning() == true)
            {
                WindowsServiceStatusLabelItem.Image = Properties.Resources.bullet_green;
            }
            else
            {
                WindowsServiceStatusLabelItem.Image = Properties.Resources.bullet_yellow;
            }
            WindowsServiceMenuItem.DropDownItems.Add(WindowsServiceStatusLabelItem);

            WindowsServiceMenuItem.DropDownItems.Add("-");

            WindowsServiceMenuItem.Image = Properties.Resources.bullet_yellow;

            ToolStripMenuItem RefreshServiceSettingsMenuItem = new ToolStripMenuItem();

            RefreshServiceSettingsMenuItem.Text        = "Refresh Service Settings";
            RefreshServiceSettingsMenuItem.ToolTipText = "The Drawbridge service must keep a separate copy of the Drawbridge settings. This button syncs the settings to the service process.";
            RefreshServiceSettingsMenuItem.Click      += delegate(Object sender, EventArgs e)
            {
                Registry.CopyUserToHKLM();
                MessageBox.Show("Done! Service is now updated.");
            };
            if (StaticHelpers.IsAdministrator() == false)
            {
                RefreshServiceSettingsMenuItem.Enabled     = false;
                RefreshServiceSettingsMenuItem.ToolTipText = "You must re-launch Drawbridge as an administrator";
            }
            WindowsServiceMenuItem.DropDownItems.Add(RefreshServiceSettingsMenuItem);

            if (StaticHelpers.IsServiceInstalled() == true)
            {
                if (StaticHelpers.IsServiceRunning() == false)
                {
                    ToolStripMenuItem StartServiceMenuItem = new ToolStripMenuItem();
                    StartServiceMenuItem.Text   = "Start Service";
                    StartServiceMenuItem.Click += delegate(Object sender, EventArgs e)
                    {
                        // Write out the settings path folder so that service knows where to look
                        Registry.CopyUserToHKLM();

                        TimeSpan          timeout = TimeSpan.FromMilliseconds(10000);
                        ServiceController service = new ServiceController("Drawbridge");
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                        MessageBox.Show("Drawbridge service has been started.");
                        RefreshMenuItem_Click(null, null);
                    };
                    if (StaticHelpers.IsAdministrator() == false)
                    {
                        StartServiceMenuItem.Enabled     = false;
                        StartServiceMenuItem.ToolTipText = "You must re-launch Drawbridge as an administrator";
                    }
                    WindowsServiceMenuItem.DropDownItems.Add(StartServiceMenuItem);
                }
                else
                {
                    WindowsServiceMenuItem.Image = Properties.Resources.bullet_green;
                    ToolStripMenuItem StartServiceMenuItem = new ToolStripMenuItem();
                    StartServiceMenuItem.Text   = "Stop Service";
                    StartServiceMenuItem.Click += delegate(Object sender, EventArgs e)
                    {
                        TimeSpan          timeout = TimeSpan.FromMilliseconds(10000);
                        ServiceController service = new ServiceController("Drawbridge");
                        service.Stop();
                        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                        MessageBox.Show("Drawbridge service has been stopped.");
                        RefreshMenuItem_Click(null, null);
                    };
                    if (StaticHelpers.IsAdministrator() == false)
                    {
                        StartServiceMenuItem.Enabled     = false;
                        StartServiceMenuItem.ToolTipText = "You must re-launch Drawbridge as an administrator";
                    }
                    WindowsServiceMenuItem.DropDownItems.Add(StartServiceMenuItem);
                }

                ToolStripMenuItem UninstallServiceMenuItem = new ToolStripMenuItem();
                UninstallServiceMenuItem.Text    = "Uninstall Service";
                UninstallServiceMenuItem.Enabled = StaticHelpers.IsAdministrator();
                if (StaticHelpers.IsAdministrator() == false)
                {
                    UninstallServiceMenuItem.Enabled     = false;
                    UninstallServiceMenuItem.ToolTipText = "You must re-launch Drawbridge as an administrator";
                }
                UninstallServiceMenuItem.Click += delegate(Object sender, EventArgs e)
                {
                    string           path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\WindowsService.exe";
                    ProcessStartInfo psi  = new ProcessStartInfo();
                    psi.Arguments = "/K sc.exe delete Drawbridge";
                    psi.FileName  = "CMD.EXE";
                    psi.Verb      = "runas";
                    Process p = Process.Start(psi);
                    MessageBox.Show("Drawbridge service has been deleted.");
                    RefreshMenuItem_Click(null, null);
                };
                WindowsServiceMenuItem.DropDownItems.Add(UninstallServiceMenuItem);
            }
            else
            {
                ToolStripMenuItem InstallServiceMenuItem = new ToolStripMenuItem();
                InstallServiceMenuItem.Text = "Install Service";
                if (StaticHelpers.IsAdministrator() == false)
                {
                    InstallServiceMenuItem.Enabled     = false;
                    InstallServiceMenuItem.ToolTipText = "You must re-launch Drawbridge as an administrator";
                }
                InstallServiceMenuItem.Click += delegate(Object sender, EventArgs e)
                {
                    // Write out the settings path folder so that service knows where to look
                    Registry.CopyUserToHKLM();

                    string           path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\WindowsService.exe";
                    ProcessStartInfo psi  = new ProcessStartInfo();
                    psi.Arguments = String.Format("/K sc.exe create \"Drawbridge\" binPath= \"{0}\" start= \"auto\"", path);
                    psi.FileName  = "CMD.EXE";
                    psi.Verb      = "runas";
                    Process p = Process.Start(psi);
                    MessageBox.Show("Drawbridge service has been created.");
                    RefreshMenuItem_Click(null, null);
                };
                WindowsServiceMenuItem.DropDownItems.Add(InstallServiceMenuItem);
            }
        }