Example #1
0
        public bool Reset(string key, string thumbprint)
        {
            Logger.Info("Resetting Server Key");
            var entropy = new byte[16];

            new RNGCryptoServiceProvider().GetBytes(entropy);
            var serverKeyBytes = Encoding.ASCII.GetBytes(key);
            var encryptedKey   = ServiceDP.EncryptData(serverKeyBytes, true, entropy);

            var serviceSetting   = new ServiceSetting();
            var serverKeyEntropy = serviceSetting.GetSetting("server_key_entropy");

            serverKeyEntropy.Value = Convert.ToBase64String(entropy);
            serviceSetting.UpdateSettingValue(serverKeyEntropy);

            var serverKey = serviceSetting.GetSetting("server_key");

            serverKey.Value = Convert.ToBase64String(encryptedKey);
            serviceSetting.UpdateSettingValue(serverKey);


            var caThumbprint = serviceSetting.GetSetting("ca_thumbprint");

            caThumbprint.Value = thumbprint;
            serviceSetting.UpdateSettingValue(caThumbprint);

            Logger.Info("Resetting Server Key Finished");
            return(true);
        }
Example #2
0
        public TClass ExecuteSymKeyEncryption <TClass>(RestRequest request, string body) where TClass : new()
        {
            request.AddHeader("client", DtoGobalSettings.ClientIdentity.Name);
            request.AddHeader("identifier", DtoGobalSettings.ClientIdentity.Guid);
            var serviceSetting = new ServiceSetting();
            var entropy        = serviceSetting.GetSetting("entropy");
            var encryptedKey   = serviceSetting.GetSetting("encryption_key");
            var decryptedKey   = ServiceDP.DecryptData(Convert.FromBase64String(encryptedKey.Value), true,
                                                       Convert.FromBase64String(entropy.Value));

            if (!string.IsNullOrEmpty(body))
            {
                var encryptedContent = new ServiceSymmetricEncryption().EncryptData(decryptedKey, body);
                request.AddParameter("text/xml", encryptedContent, ParameterType.RequestBody);
            }

            var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint");
            var deviceCert       = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My);

            if (deviceCert == null)
            {
                return(default(TClass));
            }

            var encryptedCert = new ServiceSymmetricEncryption().EncryptData(decryptedKey,
                                                                             Convert.ToBase64String(deviceCert.RawData));

            request.AddHeader("device_cert", Convert.ToBase64String(encryptedCert));

            return(SubmitRequest <TClass>(request, decryptedKey));
        }
Example #3
0
        private void UpdateComServers(List <DtoClientComServers> comServers)
        {
            var settingService = new ServiceSetting();
            var activeString   = "";

            foreach (var server in comServers.Where(x => x.Role.Equals("Active")))
            {
                activeString += server.Url + ",";
            }
            var trimmedActive = activeString.Trim(',');

            var passiveString = "";

            foreach (var server in comServers.Where(x => x.Role.Equals("Passive")))
            {
                passiveString += server.Url + ",";
            }
            var trimmedPassive = passiveString.Trim(',');

            if (!string.IsNullOrEmpty(trimmedActive))
            {
                var currentActive = settingService.GetSetting("active_com_servers");
                currentActive.Value = trimmedActive;
                settingService.UpdateSettingValue(currentActive);
            }

            if (!string.IsNullOrEmpty(trimmedPassive))
            {
                var currentPassive = settingService.GetSetting("passive_com_servers");
                currentPassive.Value = trimmedPassive;
                settingService.UpdateSettingValue(currentPassive);
            }
        }
Example #4
0
        public DtoClientStartupInfo GetStartupInfo()
        {
            var settingService = new ServiceSetting();
            var startupInfo    = new DtoClientStartupInfo();

            startupInfo.DelayType =
                (EnumStartupDelay.DelayType)
                Convert.ToInt16(settingService.GetSetting(SettingStrings.StartupDelayType).Value);
            startupInfo.SubDelay        = settingService.GetSetting(SettingStrings.StartupDelaySub).Value;
            startupInfo.ThresholdWindow = settingService.GetSetting(SettingStrings.ThresholdWindow).Value;

            var versions = new ServiceVersion().GetVersions();

            if (versions == null)
            {
                startupInfo.IsError      = true;
                startupInfo.ErrorMessage = "Could Not Determine Server Version";
                return(startupInfo);
            }

            if (!versions.ExpectedToecApiVersion.Equals(ToecApiStrings.ToecApiVersion))
            {
                startupInfo.IsError      = true;
                startupInfo.ErrorMessage = "Toec Api Version And Database Version Do Not Match.  The Toec Api Server May Need Updated.";
                return(startupInfo);
            }


            startupInfo.ExpectedClientVersion = versions.LatestClientVersion;
            return(startupInfo);
        }
Example #5
0
        public bool DownloadFile(RestRequest request, string body, string destination)
        {
            if (string.IsNullOrEmpty(body))
            {
                throw new ArgumentException("body");
            }

            request.AddHeader("client", DtoGobalSettings.ClientIdentity.Name);
            request.AddHeader("identifier", DtoGobalSettings.ClientIdentity.Guid);
            var serviceSetting = new ServiceSetting();
            var entropy        = serviceSetting.GetSetting("entropy");
            var encryptedKey   = serviceSetting.GetSetting("encryption_key");
            var decryptedKey   = ServiceDP.DecryptData(Convert.FromBase64String(encryptedKey.Value), true,
                                                       Convert.FromBase64String(entropy.Value));

            var encryptedContent = new ServiceSymmetricEncryption().EncryptData(decryptedKey, body);

            request.AddParameter("text/xml", encryptedContent, ParameterType.RequestBody);

            var deviceThumbprint = new ServiceSetting().GetSetting("device_thumbprint");
            var deviceCert       = ServiceCertificate.GetCertificateFromStore(deviceThumbprint.Value, StoreName.My);

            if (deviceCert == null)
            {
                return(false);
            }
            var encryptedCert = new ServiceSymmetricEncryption().EncryptData(decryptedKey,
                                                                             Convert.ToBase64String(deviceCert.RawData));

            request.AddHeader("device_cert", Convert.ToBase64String(encryptedCert));

            try
            {
                _log.Debug(request.Resource);
                using (var stream = File.Create(destination, 4096))
                {
                    request.ResponseWriter = (responseStream) => responseStream.CopyTo(stream);
                    _client.DownloadData(request);
                    if (stream.Length == 0)
                    {
                        //something went wrong, rest sharp can't display any other info with downloaddata, so we don't know why
                        return(false);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                _log.Error("Could Not Save File: " + destination);
                _log.Error(ex.Message);
                return(false);
            }
        }
Example #6
0
        public TClass ExecuteHMAC <TClass>(RestRequest request, string computerName) where TClass : new()
        {
            //Calculate UNIX time
            var epochStart       = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
            var timeSpan         = DateTime.UtcNow - epochStart;
            var requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();

            var nonce = Guid.NewGuid().ToString("N");

            var url =
                HttpUtility.UrlEncode(_client.BaseUrl + request.Resource).ToLower();

            var body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            var requestContentBase64String = string.Empty;

            if (body != null)
            {
                var content            = Encoding.ASCII.GetBytes(body.Value.ToString());
                var md5                = MD5.Create();
                var requestContentHash = md5.ComputeHash(content);
                requestContentBase64String = Convert.ToBase64String(requestContentHash);
            }

            var signatureRawData = string.Format("{0}{1}{2}{3}{4}{5}", computerName, request.Method, url,
                                                 requestTimeStamp, nonce, requestContentBase64String);
            var serviceSetting     = new ServiceSetting();
            var serverKeyEntropy   = serviceSetting.GetSetting("server_key_entropy");
            var encryptedServerKey = serviceSetting.GetSetting("server_key");
            var decryptedServerKey = ServiceDP.DecryptData(Convert.FromBase64String(encryptedServerKey.Value), true,
                                                           Convert.FromBase64String(serverKeyEntropy.Value));

            var    signature = Encoding.UTF8.GetBytes(signatureRawData);
            string requestSignatureBase64String;

            using (var hmac = new HMACSHA256(decryptedServerKey))
            {
                var signatureBytes = hmac.ComputeHash(signature);
                requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
            }

            request.AddHeader("Authorization",
                              "amx " +
                              string.Format("{0}:{1}:{2}:{3}", computerName, requestSignatureBase64String, nonce, requestTimeStamp));
            return(SubmitRequest <TClass>(request));
        }
Example #7
0
        public bool NetUseWithCredentials()
        {
            var settingService = new ServiceSetting();

            if (settingService.GetSetting(SettingStrings.StorageType).Value == "Local")
            {
                return(true);
            }
            sUNCPath  = settingService.GetSetting(SettingStrings.StoragePath).Value.TrimEnd('\\'); //dont' know why, but mount fails if path ends with \
            sUser     = settingService.GetSetting(SettingStrings.StorageUsername).Value;
            sPassword =
                new EncryptionServices().DecryptText(settingService.GetSetting(SettingStrings.StoragePassword).Value);
            sDomain = settingService.GetSetting(SettingStrings.StorageDomain).Value;
            uint returncode;

            try
            {
                var useinfo = new USE_INFO_2();

                useinfo.ui2_remote     = sUNCPath;
                useinfo.ui2_username   = sUser;
                useinfo.ui2_domainname = sDomain;
                useinfo.ui2_password   = sPassword;
                useinfo.ui2_asg_type   = 0;
                useinfo.ui2_usecount   = 1;
                uint paramErrorIndex;
                returncode = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);
                LastError  = (int)returncode;
                if (returncode != 1219 && returncode != 0)
                {
                    Logger.Error("Could Not Connect To Storage Location: " + sUNCPath);
                    Logger.Error("Error Code: " + returncode);
                }
                return(returncode == 0);
            }
            catch (Exception ex)
            {
                LastError = Marshal.GetLastWin32Error();
                Logger.Error("Could Not Connect To Share");
                Logger.Error(ex.Message);
                return(false);
            }
        }
Example #8
0
        private void VerifyInstallationId()
        {
            var serviceSetting = new ServiceSetting();

            Logger.Info("Verifying Installation ID");
            var status    = serviceSetting.GetSetting("provision_status");
            var installID = serviceSetting.GetSetting("installation_id");

            Logger.Info("Provision Status: " + status.Value);
            Logger.Info("Installation ID: " + installID.Value);
            if (string.IsNullOrEmpty(installID.Value) && status.Value.Equals("0"))
            {
                //from prepare image arg, generate new id
                Logger.Info("Generating New Installation ID");
                installID.Value = Guid.NewGuid().ToString();
                serviceSetting.UpdateSettingValue(installID);
            }
            Logger.Info("Verification Complete");
        }
Example #9
0
        private void VerifyComServersDefined()
        {
            var serviceSetting = new ServiceSetting();
            //no active com servers found, check for initial com servers
            var initialComServers = serviceSetting.GetSetting("initial_com_servers").Value;

            if (!string.IsNullOrEmpty(initialComServers))
            {
                return;
            }

            var activeComServers = serviceSetting.GetSetting("active_com_servers").Value;

            if (!string.IsNullOrEmpty(activeComServers))
            {
                return;
            }

            Logger.Error("No Client Com Servers Defined.  Service Cannot Continue.  Exiting....");
            Task.Delay(10 * 1000).Wait();
            Environment.Exit(1);
        }
Example #10
0
        public bool HardReset(string type)
        {
            Logger.Info("Resetting Toec: " + type);
            ServiceCertificate.DeleteAllDeviceCertificates();
            ServiceCertificate.DeleteIntermediate();

            var serviceSetting  = new ServiceSetting();
            var provisionStatus = serviceSetting.GetSetting("provision_status");

            provisionStatus.Value = "0";
            serviceSetting.UpdateSettingValue(provisionStatus);

            if (type.Equals("Full"))
            {
                var installationId = serviceSetting.GetSetting("installation_id");
                installationId.Value = Guid.NewGuid().ToString();
                serviceSetting.UpdateSettingValue(installationId);
            }

            var encryptionKey = serviceSetting.GetSetting("encryption_key");

            encryptionKey.Value = null;
            serviceSetting.UpdateSettingValue(encryptionKey);

            var entropy = serviceSetting.GetSetting("entropy");

            entropy.Value = null;
            serviceSetting.UpdateSettingValue(entropy);

            var computerIdentifier = serviceSetting.GetSetting("computer_identifier");

            computerIdentifier.Value = null;
            serviceSetting.UpdateSettingValue(computerIdentifier);

            var deviceThumbprint = serviceSetting.GetSetting("device_thumbprint");

            deviceThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(deviceThumbprint);

            var intermediateThumbprint = serviceSetting.GetSetting("intermediate_thumbprint");

            intermediateThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(intermediateThumbprint);

            if (type.Equals("Full"))
            {
                new PolicyHistoryServices().DeleteAll();
                new ServiceUserTracker().DeleteAll();
                new ServiceAppMonitor().DeleteAll();
            }

            Logger.Info("Resetting Toec Finished");
            return(true);
        }
Example #11
0
        public EnumProvisionStatus.Status ProvisionClient()
        {
            var provisionStatusString = _serviceSetting.GetSetting("provision_status");

            EnumProvisionStatus.Status provisionStatus;

            if (string.IsNullOrEmpty(provisionStatusString.Value))
            {
                provisionStatus = EnumProvisionStatus.Status.NotStarted;
            }
            else
            {
                provisionStatus = (EnumProvisionStatus.Status)Convert.ToInt16(provisionStatusString.Value);
            }

            if (provisionStatus == EnumProvisionStatus.Status.NotStarted)
            {
                var stage1Result = ProvisionStage1();
                if (stage1Result == EnumProvisionStatus.Status.IntermediateInstalled)
                {
                    var stage2Result = ProvisionStage2();
                    if (stage2Result == EnumProvisionStatus.Status.PendingConfirmation)
                    {
                        return(ProvisionStage3());
                    }
                    return(stage2Result);
                }
                return(stage1Result);
            }

            if (provisionStatus == EnumProvisionStatus.Status.IntermediateInstalled ||
                provisionStatus == EnumProvisionStatus.Status.PendingPreProvision ||
                provisionStatus == EnumProvisionStatus.Status.PendingProvisionApproval ||
                provisionStatus == EnumProvisionStatus.Status.PendingReset)
            {
                var stage2Result = ProvisionStage2();
                if (stage2Result == EnumProvisionStatus.Status.PendingConfirmation)
                {
                    return(ProvisionStage3());
                }
                return(stage2Result);
            }

            if (provisionStatus == EnumProvisionStatus.Status.PendingConfirmation)
            {
                return(ProvisionStage3());
            }

            if (provisionStatus == EnumProvisionStatus.Status.Provisioned)
            {
                return(RenewSymmKey());
            }

            return(EnumProvisionStatus.Status.Error);
        }
Example #12
0
        private void ResetToec()
        {
            if (!_imagePrepOptions.ResetToec)
            {
                return;
            }
            Logger.Info("Resetting Toec");

            ServiceCertificate.DeleteAllDeviceCertificates();
            ServiceCertificate.DeleteIntermediate();

            var serviceSetting = new ServiceSetting();

            var installationId = serviceSetting.GetSetting("installation_id");

            installationId.Value = null;
            serviceSetting.UpdateSettingValue(installationId);


            var encryptionKey = serviceSetting.GetSetting("encryption_key");

            encryptionKey.Value = null;
            serviceSetting.UpdateSettingValue(encryptionKey);

            var entropy = serviceSetting.GetSetting("entropy");

            entropy.Value = null;
            serviceSetting.UpdateSettingValue(entropy);

            var computerIdentifier = serviceSetting.GetSetting("computer_identifier");

            computerIdentifier.Value = null;
            serviceSetting.UpdateSettingValue(computerIdentifier);

            var deviceThumbprint = serviceSetting.GetSetting("device_thumbprint");

            deviceThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(deviceThumbprint);

            var intermediateThumbprint = serviceSetting.GetSetting("intermediate_thumbprint");

            intermediateThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(intermediateThumbprint);

            new PolicyHistoryServices().DeleteAll();
            new ServiceUserTracker().DeleteAll();
            new ServiceAppMonitor().DeleteAll();

            var provisionStatus = serviceSetting.GetSetting("provision_status");

            provisionStatus.Value = "0";
            serviceSetting.UpdateSettingValue(provisionStatus);


            var updatedStatus = serviceSetting.GetSetting("provision_status");
            var updatedId     = installationId = serviceSetting.GetSetting("installation_id");

            if (!updatedStatus.Value.Equals("0") && !string.IsNullOrEmpty(updatedId.Value))
            {
                Logger.Error("Prepare Image Failed.  Could Not Reset ID's");
            }

            Logger.Info("Finished Resetting Toec");
        }
Example #13
0
        public bool Set()
        {
            while (true)
            {
                Logger.Debug("Trying To Establish Client Com Server");

                //Check if active com servers have been defined

                var activeComServers  = _serviceSetting.GetSetting("active_com_servers").Value;
                var initialComServers = _serviceSetting.GetSetting("initial_com_servers").Value;
                var passiveComServers = _serviceSetting.GetSetting("passive_com_servers").Value;
                if (!string.IsNullOrEmpty(activeComServers))
                {
                    _comServers = activeComServers.Split(',').ToList();
                }

                RemoveInvalidUris();

                if (!TestConnectionForActive())
                {
                    Logger.Debug("Could Not Connect To Any Active Com Servers, Falling Back To Passive Com Servers");

                    if (!string.IsNullOrEmpty(passiveComServers))
                    {
                        _comServers = passiveComServers.Split(',').ToList();
                    }

                    RemoveInvalidUris();

                    if (!TestConnection())
                    {
                        Logger.Debug("Could Not Connect To Any Passive Com Servers, Falling Back To Initial Com Servers");

                        if (!string.IsNullOrEmpty(initialComServers))
                        {
                            _comServers = initialComServers.Split(',').ToList();
                        }

                        RemoveInvalidUris();

                        if (!TestConnection())
                        {
                            Logger.Debug("Could Not Connect To Any Initial Com Servers");
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }

                Logger.Error("Could Not Connect To Any Client Com Servers.  Delaying 30 Seconds Before Next Retry.");
                Task.Delay(30 * 1000).Wait();
            }

            Logger.Debug("Com Server Set To: " + DtoGobalSettings.ComServer);
            return(true);
        }
Example #14
0
        public bool Run()
        {
            Logger.Info("Preparing Toec For Image: ");
            Logger.Info("Checking Toec Service");
            var servResult = new ServiceSystemService().StopToec();

            if (!servResult)
            {
                Logger.Error("Toec Service Must Be Stopped Before Preparing Image.");
                return(false);
            }

            //Wait another 30 secs for anything to finish
            Logger.Info("Resetting Toec ...");
            System.Threading.Thread.Sleep(30000);

            ServiceCertificate.DeleteAllDeviceCertificates();
            ServiceCertificate.DeleteIntermediate();

            var serviceSetting = new ServiceSetting();

            var installationId = serviceSetting.GetSetting("installation_id");

            installationId.Value = null;
            serviceSetting.UpdateSettingValue(installationId);


            var encryptionKey = serviceSetting.GetSetting("encryption_key");

            encryptionKey.Value = null;
            serviceSetting.UpdateSettingValue(encryptionKey);

            var entropy = serviceSetting.GetSetting("entropy");

            entropy.Value = null;
            serviceSetting.UpdateSettingValue(entropy);

            var computerIdentifier = serviceSetting.GetSetting("computer_identifier");

            computerIdentifier.Value = null;
            serviceSetting.UpdateSettingValue(computerIdentifier);

            var deviceThumbprint = serviceSetting.GetSetting("device_thumbprint");

            deviceThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(deviceThumbprint);

            var intermediateThumbprint = serviceSetting.GetSetting("intermediate_thumbprint");

            intermediateThumbprint.Value = null;
            serviceSetting.UpdateSettingValue(intermediateThumbprint);

            new PolicyHistoryServices().DeleteAll();
            new ServiceUserTracker().DeleteAll();
            new ServiceAppMonitor().DeleteAll();

            var provisionStatus = serviceSetting.GetSetting("provision_status");

            provisionStatus.Value = "0";
            serviceSetting.UpdateSettingValue(provisionStatus);


            var updatedStatus = serviceSetting.GetSetting("provision_status");
            var updatedId     = installationId = serviceSetting.GetSetting("installation_id");

            if (!updatedStatus.Value.Equals("0") && !string.IsNullOrEmpty(updatedId.Value))
            {
                Logger.Error("Prepare Image Failed.  Could Not Reset ID's");
                return(false);
            }


            Logger.Info("Toec Prepare Image Finished");
            return(true);
        }
Example #15
0
 public string VerifyDb()
 {
     return(_settingServices.GetSetting(SettingStrings.CheckinInterval).Value);
 }