Exemple #1
0
        public static void Load(ResultMachine machine)
        {
            //if confgigured, try to set machine.name based on some vmtools.exe value
            try
            {
                if (Program.Configuration.IdFormat.Equals("guestinfo", StringComparison.InvariantCultureIgnoreCase))
                {
                    var p = new Process();
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;

                    p.StartInfo.FileName  = $"{Program.Configuration.VMWareToolsLocation}";
                    p.StartInfo.Arguments = $"--cmd \"info-get {Program.Configuration.IdFormatKey}\"";

                    p.Start();

                    var output = p.StandardOutput.ReadToEnd().Trim();
                    p.WaitForExit();

                    if (!string.IsNullOrEmpty(output))
                    {
                        var o = Program.Configuration.IdFormatValue;
                        o = o.Replace("$formatkeyvalue$", output);
                        o = o.Replace("$machinename$", machine.Name);

                        machine.SetName(o);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Debug(e);
            }
        }
Exemple #2
0
        private static WebClient BuildEx(ResultMachine machine, bool hasId = true)
        {
            var client = new WebClient();

            client.Headers.Add(HttpRequestHeader.UserAgent, "Ghosts Client");
            if (hasId)
            {
                client.Headers.Add("ghosts-id", CheckId.Id);
            }
            client.Headers.Add("ghosts-name", machine.Name);
            client.Headers.Add("ghosts-fqdn", machine.FQDN);
            client.Headers.Add("ghosts-host", machine.Host);
            client.Headers.Add("ghosts-domain", machine.Domain);
            client.Headers.Add("ghosts-resolvedhost", machine.ResolvedHost);
            client.Headers.Add("ghosts-ip", machine.ClientIp);

            var username = machine.CurrentUsername;

            if (Program.Configuration.EncodeHeaders)
            {
                username = Base64Encoder.Base64Encode(username);
            }

            client.Headers.Add("ghosts-user", username);
            client.Headers.Add("ghosts-version", ApplicationDetails.Version);
            return(client);
        }
Exemple #3
0
        /// <summary>
        /// API call to get client ID (probably based on hostname, but configurable) and saves it locally
        /// </summary>
        /// <returns></returns>
        private static string Run()
        {
            // ignore all certs
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var s = string.Empty;

            if (!Program.Configuration.IdEnabled)
            {
                return(s);
            }

            var machine = new ResultMachine();

            GuestInfoVars.Load(machine);

            //call home
            using (WebClient client = WebClientBuilder.BuildNoId(machine))
            {
                try
                {
                    using (StreamReader reader =
                               new StreamReader(client.OpenRead(Program.Configuration.IdUrl)))
                    {
                        s = reader.ReadToEnd();
                        _log.Debug($"{DateTime.Now} - Received client ID");
                    }
                }
                catch (WebException wex)
                {
                    if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        _log.Debug("No ID returned!", wex);
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e);
                }
            }

            s = s.Replace("\"", "");

            if (!Directory.Exists(ApplicationDetails.InstanceFiles.Path))
            {
                Directory.CreateDirectory(ApplicationDetails.InstanceFiles.Path);
            }

            if (string.IsNullOrEmpty(s))
            {
                return(string.Empty);
            }

            //save returned id
            File.WriteAllText(ConfigFile, s);
            return(s);
        }
Exemple #4
0
        public static void Report(object payload, string uri)
        {
            var machine = new ResultMachine();

            using (var client = WebClientBuilder.Build(machine))
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.UploadString(uri, JsonConvert.SerializeObject(payload));
            }
        }
Exemple #5
0
        private static void PostClientResults()
        {
            if (!Program.Configuration.ClientResults.IsEnabled)
            {
                return;
            }

            var fileName   = ApplicationDetails.LogFiles.ClientUpdates;
            var cyclesleep = Program.Configuration.ClientResults.CycleSleep;
            var posturl    = Program.Configuration.ClientResults.PostUrl;

            var machine = new ResultMachine();

            Thread.Sleep(cyclesleep);

            while (true)
            {
                try
                {
                    if (File.Exists(fileName))
                    {
                        PostResults(fileName, machine, posturl);
                    }
                    else
                    {
                        _log.Trace($"{DateTime.Now} - {fileName} not found - sleeping...");
                    }
                }
                catch (Exception e)
                {
                    _log.Error($"Problem posting logs to server {e}");
                }

                // look for other result files that have not been posted
                try
                {
                    foreach (var file in Directory.GetFiles(Path.GetDirectoryName(fileName)))
                    {
                        if (!file.EndsWith("app.log") && file != fileName)
                        {
                            PostResults(file, machine, posturl, true);
                        }
                    }
                }
                catch (Exception e)
                {
                    _log.Debug($"Problem posting overflow logs from {fileName} to server {posturl}: {e}");
                }

                Thread.Sleep(cyclesleep);
            }
        }
Exemple #6
0
        /// <summary>
        /// API call to get client ID (probably based on hostname, but configurable) and saves it locally
        /// </summary>
        /// <returns></returns>
        private static string Run()
        {
            var s = string.Empty;

            if (!Program.Configuration.IdEnabled)
            {
                return(s);
            }

            var machine = new ResultMachine();

            //call home
            using (var client = WebClientBuilder.BuildNoId(machine))
            {
                try
                {
                    using (var reader =
                               new StreamReader(client.OpenRead(Program.Configuration.IdUrl)))
                    {
                        s = reader.ReadToEnd();
                        _log.Debug($"{DateTime.Now} - Received client ID");
                    }
                }
                catch (WebException wex)
                {
                    if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        _log.Debug("No ID returned!", wex);
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e);
                }
            }

            s = s.Replace("\"", "");

            if (!Directory.Exists(ApplicationDetails.InstanceFiles.Path))
            {
                Directory.CreateDirectory(ApplicationDetails.InstanceFiles.Path);
            }

            //save returned id
            File.WriteAllText(ConfigFile, s);
            return(s);
        }
Exemple #7
0
        internal static void PostSurvey()
        {
            try
            {
                _log.Trace("posting survey");

                var posturl = Program.Configuration.Survey.PostUrl;

                if (!File.Exists(ApplicationDetails.InstanceFiles.SurveyResults))
                {
                    return;
                }

                var survey = JsonConvert.DeserializeObject <Ghosts.Domain.Messages.MesssagesForServer.Survey>(File.ReadAllText(ApplicationDetails.InstanceFiles.SurveyResults));

                var payload = JsonConvert.SerializeObject(survey);

                var machine = new ResultMachine();

                if (Program.Configuration.Survey.IsSecure)
                {
                    payload = Crypto.EncryptStringAes(payload, machine.Name);
                    payload = Base64Encoder.Base64Encode(payload);

                    var p = new EncryptedPayload();
                    p.Payload = payload;

                    payload = JsonConvert.SerializeObject(p);
                }

                using (var client = WebClientBuilder.Build(machine))
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    client.UploadString(posturl, payload);
                }

                _log.Trace($"{DateTime.Now} - survey posted to server successfully");

                File.Delete(ApplicationDetails.InstanceFiles.SurveyResults);
            }
            catch (Exception e)
            {
                _log.Trace("Problem posting logs to server");
                _log.Error(e);
            }
        }
Exemple #8
0
        private static WebClient BuildEx(ResultMachine machine, bool hasId = true)
        {
            var client = new WebClient();

            if (hasId)
            {
                client.Headers.Add("ghosts-id", CheckId.Id);
            }
            client.Headers.Add("ghosts-name", machine.Name);
            client.Headers.Add("ghosts-fqdn", machine.FQDN);
            client.Headers.Add("ghosts-host", machine.Host);
            client.Headers.Add("ghosts-domain", machine.Domain);
            client.Headers.Add("ghosts-resolvedhost", machine.ResolvedHost);
            client.Headers.Add("ghosts-ip", machine.ClientIp);
            client.Headers.Add("ghosts-user", machine.CurrentUsername);
            client.Headers.Add("ghosts-version", ApplicationDetails.Version);
            return(client);
        }
Exemple #9
0
        private static void PostResults(string fileName, ResultMachine machine, string postUrl, bool isDeletable = false)
        {
            var sb   = new StringBuilder();
            var data = File.ReadLines(fileName);

            foreach (var d in data)
            {
                sb.AppendLine(d);
            }

            var r = new TransferLogDump();

            r.Log = sb.ToString();

            var payload = JsonConvert.SerializeObject(r);

            if (Program.Configuration.ClientResults.IsSecure)
            {
                payload = Crypto.EncryptStringAes(payload, machine.Name);
                payload = Base64Encoder.Base64Encode(payload);

                var p = new EncryptedPayload();
                p.Payload = payload;

                payload = JsonConvert.SerializeObject(p);
            }

            using (var client = WebClientBuilder.Build(machine))
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.UploadString(postUrl, payload);
            }

            if (isDeletable)
            {
                File.Delete(fileName);
            }
            else
            {
                File.WriteAllText(fileName, string.Empty);
            }

            _log.Trace($"{DateTime.Now} - {fileName} posted to server successfully");
        }
Exemple #10
0
        private static void PostCurrentTimeline()
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var posturl = string.Empty;

            try
            {
                posturl = Program.Configuration.IdUrl.Replace("clientid", "clienttimeline");
            }
            catch (Exception exc)
            {
                _log.Error("Can't get timeline posturl!");
                return;
            }

            try
            {
                _log.Trace("posting timeline");

                var payload = File.ReadAllText(ApplicationDetails.ConfigurationFiles.Timeline);
                var machine = new ResultMachine();
                GuestInfoVars.Load(machine);

                using (var client = WebClientBuilder.Build(machine))
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    client.UploadString(posturl, JsonConvert.SerializeObject(payload));
                }

                _log.Trace($"{DateTime.Now} - timeline posted to server successfully");
            }
            catch (Exception e)
            {
                _log.Debug($"Problem posting timeline to server from { ApplicationDetails.ConfigurationFiles.Timeline } to { posturl }");
                _log.Error(e);
            }
        }
Exemple #11
0
 public static WebClient BuildNoId(ResultMachine machine)
 {
     return(BuildEx(machine, false));
 }
Exemple #12
0
        private static void GetServerUpdates()
        {
            if (!Program.Configuration.ClientUpdates.IsEnabled)
            {
                return;
            }

            var machine = new ResultMachine();

            Thread.Sleep(Program.Configuration.ClientUpdates.CycleSleep);

            while (true)
            {
                try
                {
                    string s = string.Empty;
                    using (var client = WebClientBuilder.Build(machine))
                    {
                        try
                        {
                            using (var reader =
                                       new StreamReader(client.OpenRead(Program.Configuration.ClientUpdates.PostUrl)))
                            {
                                s = reader.ReadToEnd();
                                _log.Debug($"{DateTime.Now} - Received new configuration");
                            }
                        }
                        catch (WebException wex)
                        {
                            if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                            {
                                _log.Debug($"{DateTime.Now} - No new configuration found");
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }
                    }

                    if (!string.IsNullOrEmpty(s))
                    {
                        var update = JsonConvert.DeserializeObject <UpdateClientConfig>(s);

                        switch (update.Type)
                        {
                        case UpdateClientConfig.UpdateType.Timeline:
                            TimelineBuilder.SetLocalTimeline(update.Update.ToString());
                            break;

                        case UpdateClientConfig.UpdateType.TimelinePartial:
                            try
                            {
                                var timeline = JsonConvert.DeserializeObject <Timeline>(update.Update.ToString());

                                foreach (var timelineHandler in timeline.TimeLineHandlers)
                                {
                                    _log.Trace($"PartialTimeline found: {timelineHandler.HandlerType}");

                                    foreach (var timelineEvent in timelineHandler.TimeLineEvents)
                                    {
                                        if (string.IsNullOrEmpty(timelineEvent.TrackableId))
                                        {
                                            timelineEvent.TrackableId = Guid.NewGuid().ToString();
                                        }
                                    }

                                    var orchestrator = new Orchestrator();
                                    orchestrator.RunCommand(timelineHandler);
                                }
                            }
                            catch (Exception exc)
                            {
                                _log.Debug(exc);
                            }

                            break;

                        case UpdateClientConfig.UpdateType.Health:
                        {
                            var newTimeline = JsonConvert.DeserializeObject <Ghosts.Domain.ResultHealth>(update.Update.ToString());
                            //save to local disk
                            using (var file = File.CreateText(ApplicationDetails.ConfigurationFiles.Health))
                            {
                                var serializer = new JsonSerializer();
                                serializer.Formatting = Formatting.Indented;
                                serializer.Serialize(file, newTimeline);
                            }

                            break;
                        }

                        default:
                        {
                            _log.Debug($"Update {update.Type} has no handler, ignoring...");
                            break;
                        }
                        }
                    }
                }
                catch (Exception e)
                {
                    _log.Debug("Problem polling for new configuration");
                    _log.Error(e);
                }

                Thread.Sleep(Program.Configuration.ClientUpdates.CycleSleep);
            }
        }
Exemple #13
0
        internal static void PostSurvey()
        {
            // ignore all certs
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var posturl = string.Empty;

            try
            {
                posturl = Program.Configuration.Survey.PostUrl;
            }
            catch (Exception exc)
            {
                _log.Error("Can't get survey posturl!");
                return;
            }

            try
            {
                _log.Trace("posting survey");

                Thread.Sleep(ProcessManager.Jitter(100));

                if (!File.Exists(ApplicationDetails.InstanceFiles.SurveyResults))
                {
                    return;
                }

                var survey = JsonConvert.DeserializeObject <Domain.Messages.MesssagesForServer.Survey>(File.ReadAllText(ApplicationDetails.InstanceFiles.SurveyResults));

                var payload = JsonConvert.SerializeObject(survey);

                var machine = new ResultMachine();
                GuestInfoVars.Load(machine);

                if (Program.Configuration.Survey.IsSecure)
                {
                    payload = Crypto.EncryptStringAes(payload, machine.Name);
                    payload = Base64Encoder.Base64Encode(payload);

                    var p = new EncryptedPayload();
                    p.Payload = payload;

                    payload = JsonConvert.SerializeObject(p);
                }

                using (var client = WebClientBuilder.Build(machine))
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    client.UploadString(posturl, payload);
                }

                _log.Trace($"{DateTime.Now} - survey posted to server successfully");

                File.Delete(ApplicationDetails.InstanceFiles.SurveyResults);
            }
            catch (Exception e)
            {
                _log.Debug($"Problem posting logs to server from { ApplicationDetails.InstanceFiles.SurveyResults } to { Program.Configuration.Survey.PostUrl }");
                _log.Error(e);
            }
        }
Exemple #14
0
        private static void PostClientResults()
        {
            if (!Program.Configuration.ClientResults.IsEnabled)
            {
                return;
            }

            // ignore all certs
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var fileName = ApplicationDetails.LogFiles.ClientUpdates;
            var posturl  = Program.Configuration.ClientResults.PostUrl;

            var machine = new ResultMachine();

            GuestInfoVars.Load(machine);

            Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientResults.CycleSleep));

            while (true)
            {
                try
                {
                    if (File.Exists(fileName))
                    {
                        PostResults(fileName, machine, posturl);
                    }
                    else
                    {
                        _log.Trace($"{DateTime.Now} - {fileName} not found - sleeping...");
                    }
                }
                catch (Exception e)
                {
                    _log.Error($"Problem posting logs to server {e}");
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }

                // look for other result files that have not been posted
                try
                {
                    foreach (var file in Directory.GetFiles(Path.GetDirectoryName(fileName)))
                    {
                        if (!file.EndsWith("app.log") && file != fileName)
                        {
                            PostResults(file, machine, posturl, true);
                        }
                    }
                }
                catch (Exception e)
                {
                    _log.Debug($"Problem posting overflow logs from {fileName} to server {posturl} : {e}");
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }

                Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientResults.CycleSleep));
            }
        }
Exemple #15
0
        private static void PostClientResults()
        {
            if (!Program.Configuration.ClientResults.IsEnabled)
            {
                return;
            }

            // ignore all certs
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var fileName = ApplicationDetails.LogFiles.ClientUpdates;
            var posturl  = Program.Configuration.ClientResults.PostUrl;

            var machine = new ResultMachine();

            GuestInfoVars.Load(machine);

            Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientResults.CycleSleep));

            while (true)
            {
                try
                {
                    var sb   = new StringBuilder();
                    var data = File.ReadLines(fileName);
                    foreach (var d in data)
                    {
                        sb.AppendLine(d);
                    }

                    var r = new TransferLogDump();
                    r.Log = sb.ToString();

                    var payload = JsonConvert.SerializeObject(r);

                    if (Program.Configuration.ClientResults.IsSecure)
                    {
                        payload = Crypto.EncryptStringAes(payload, machine.Name);
                        payload = Crypto.Base64Encode(payload);

                        var p = new EncryptedPayload();
                        p.Payload = payload;

                        payload = JsonConvert.SerializeObject(p);
                    }

                    using (var client = WebClientBuilder.Build(machine))
                    {
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        client.UploadString(posturl, payload);
                    }

                    File.WriteAllText(fileName, string.Empty);

                    _log.Trace($"{DateTime.Now} - {fileName} posted to server successfully");
                }
                catch (Exception e)
                {
                    _log.Debug($"Problem posting logs from { fileName } to server { posturl }");
                    _log.Error(e);
                }

                Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientResults.CycleSleep));
            }
        }
Exemple #16
0
        private static void GetServerUpdates()
        {
            if (!Program.Configuration.ClientUpdates.IsEnabled)
            {
                return;
            }

            // ignore all certs
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var machine = new ResultMachine();

            GuestInfoVars.Load(machine);

            Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientUpdates.CycleSleep));

            while (true)
            {
                try
                {
                    string s = string.Empty;
                    using (var client = WebClientBuilder.Build(machine))
                    {
                        try
                        {
                            using (var reader =
                                       new StreamReader(client.OpenRead(Program.Configuration.ClientUpdates.PostUrl)))
                            {
                                s = reader.ReadToEnd();
                                _log.Debug($"{DateTime.Now} - Received new configuration");
                            }
                        }
                        catch (WebException wex)
                        {
                            if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                            {
                                _log.Debug($"{DateTime.Now} - No new configuration found");
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }
                    }

                    if (!string.IsNullOrEmpty(s))
                    {
                        var update = JsonConvert.DeserializeObject <UpdateClientConfig>(s);

                        if (update.Type == UpdateClientConfig.UpdateType.Timeline)
                        {
                            TimelineBuilder.SetLocalTimeline(update.Update.ToString());
                        }
                        else if (update.Type == UpdateClientConfig.UpdateType.Health)
                        {
                            var newTimeline = JsonConvert.DeserializeObject <Domain.ResultHealth>(update.Update.ToString());
                            //save to local disk
                            using (var file = File.CreateText(ApplicationDetails.ConfigurationFiles.Health))
                            {
                                var serializer = new JsonSerializer();
                                serializer.Formatting = Formatting.Indented;
                                serializer.Serialize(file, newTimeline);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _log.Debug("Problem polling for new configuration");
                    _log.Error(e);
                }

                Thread.Sleep(ProcessManager.Jitter(Program.Configuration.ClientUpdates.CycleSleep));
            }
        }