Exemple #1
0
        private void InstallCertification(string certFileName, StoreName storeName, StoreLocation storeLocaion, string password, X509KeyStorageFlags x509KeyStorageFlags)
        {
            X509Store store = new X509Store(storeName, storeLocaion);

            try
            {
                bool             Exists = false;
                X509Certificate2 cert   = new X509Certificate2(certFileName, TranString.convertToSecureString(password), x509KeyStorageFlags);
                store.Open(OpenFlags.ReadWrite);
                foreach (X509Certificate2 storeCert in store.Certificates)
                {
                    if (storeCert.Thumbprint.Equals(cert.Thumbprint, StringComparison.OrdinalIgnoreCase))
                    {
                        Exists = true;
                        break;
                    }
                }
                if (!Exists)
                {
                    store.Add(cert);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                store.Close();
            }
        }
Exemple #2
0
        public void LoadUserData()
        {
            lock (LockObj)
            {
                if (!File.Exists(encryptionKeyFullFilename))
                {
                    key = GetRandomKey();

                    // write user initial config file
                    string strDataManagerContentsInitFullFilename = File.ReadAllText(dataManagerContentsInitFullFilename, Encoding.Default);
                    string strEncryptedDataManagerContentsInit    = TranString.EncodeAES(strDataManagerContentsInitFullFilename, key);
                    if (File.Exists(encryptedDataManagerContentsFullFilename))
                    {
                        File.Delete(encryptedDataManagerContentsFullFilename);
                    }
                    else
                    {
                        File.WriteAllText(encryptedDataManagerContentsFullFilename, strEncryptedDataManagerContentsInit);
                    }
                }

                // read user config file
                key = GetRandomKey();
                string CryptedConfigFile = File.ReadAllText(Path.Combine(path, encryptedDataManagerContentsFullFilename), Encoding.Default);
                string PlainConfigFile   = TranString.DecodeAES(CryptedConfigFile, key);
                string2List(PlainConfigFile, listData);
                LoadDataList2Dictionary(listData, dicData);
            }
        }
Exemple #3
0
        public void LoadUserData()
        {
            lock (LockObj)
            {
                if (!File.Exists(encryptionKeyFullFilename))
                {
                    key = GetRandomKey();

                    // write user initial config file
                    string strDataManagerContentsInitFullFilename = File.ReadAllText(dataManagerContentsInitFullFilename, Encoding.Default);
                    string strEncryptedDataManagerContentsInit    = TranString.EncodeAES(strDataManagerContentsInitFullFilename, key);
                    // 암호키를 지우면 데이터 파일을 다시 만든다.
                    if (File.Exists(encryptedDataManagerContentsFullFilename))
                    {
                        File.Delete(encryptedDataManagerContentsFullFilename);
                    }
                    File.WriteAllText(encryptedDataManagerContentsFullFilename, strEncryptedDataManagerContentsInit);
                }

                // read user config file
                key = GetRandomKey();
                string CryptedConfigFile = File.ReadAllText(Path.Combine(path, encryptedDataManagerContentsFullFilename), Encoding.Default);
                string PlainConfigFile   = TranString.DecodeAES(CryptedConfigFile, key);
                string2List(PlainConfigFile, listData);
                LoadDataList2Dictionary(listData, dicData);
                var logintype = dicData[new Tuple <Category, Key>(Category.Login, Key.LoginType)];
                LoginType = (LoginType)Enum.Parse(typeof(LoginType), logintype);
            }
        }
Exemple #4
0
        private void LoadLogClientData()
        {
            lock (LockObj)
            {
                if (!File.Exists(encryptionKeyFullFilename))
                {
                    key = GetRandomKey();

                    // write user initial config file
                    string strLogClientConfigInit          = File.ReadAllText(logClientConfigInitFullFilename, Encoding.Default);
                    string strEncryptedLogClientConfigInit = TranString.EncodeAES(strLogClientConfigInit, key);
                    if (File.Exists(encryptedlogClientConfigContentsFullFilename))
                    {
                        File.Delete(encryptedlogClientConfigContentsFullFilename);
                    }
                    File.WriteAllText(encryptedlogClientConfigContentsFullFilename, strEncryptedLogClientConfigInit);
                }

                // read user config file
                key = GetRandomKey();
                string CryptedConfigFile = File.ReadAllText(encryptedlogClientConfigContentsFullFilename, Encoding.Default);
                string PlainConfigFile   = TranString.DecodeAES(CryptedConfigFile, key);
                string2List(PlainConfigFile, listData);
                LoadDataList2Dictionary(listData, dicData);
            }
        }
Exemple #5
0
        public bool InsertTemplate(string key, string value)
        {
            bool isSuccess = false;

            try
            {
                if (!Templates.ContainsKey(key))
                {
                    Templates.Add(key, TranString.EncodeBase64Unicode(value));
                    isSuccess = true;
                }
                else
                {
                    isSuccess = false;
                }
                if (isSuccess)
                {
                    SaveTemplate();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(isSuccess);
        }
Exemple #6
0
        private void buttonDecode_Click(object sender, EventArgs e)
        {
            try
            {
                switch (algorithm)
                {
                case Algorithm.Base64Unicode:
                    textBoxDecode.Text = TranString.DecodeBase64Unicode(textBoxEncode.Text);
                    break;

                case Algorithm.Base64:
                    textBoxDecode.Text = TranString.DecodeBase64(textBoxEncode.Text);
                    break;

                case Algorithm.UrlEncode:
                    textBoxDecode.Text = TranString.DecodeUrlDecode(textBoxEncode.Text);
                    break;

                case Algorithm.AES:
                    textBoxDecode.Text = TranString.DecodeAES(textBoxEncode.Text, textBoxKey.Text);
                    break;

                case Algorithm.Rijndael:
                    textBoxDecode.Text = TranString.DecodeRijndael(textBoxEncode.Text, textBoxRijndaelKey.Text, textBoxRijndaelVector.Text);
                    break;

                default:
                    throw new ArgumentOutOfRangeException($"algorithm : {algorithm}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #7
0
        public void SaveUserData()
        {
            string        fullFilename = encryptedDataManagerContentsFullFilename;
            List <string> listName     = listData;

            lock (LockObj)
            {
                if (File.Exists(fullFilename))
                {
                    File.Delete(fullFilename);
                }


                if (LoginType.GOV == LoginType)
                {
                    dicData[new Tuple <Category, Key>(Category.Login, Key.LoginType)] = "GOV";
                }
                else
                {
                    dicData[new Tuple <Category, Key>(Category.Login, Key.LoginType)] = "Default";
                }

                var contents = new StringBuilder();

                foreach (string line in listName)
                {
                    try
                    {
                        if (line.StartsWith(@"#") || (line == null) || (line.Trim().Equals("")))
                        {
                            contents.Append(line + Environment.NewLine);
                        }
                        else
                        {
                            string[] lineValues = line.Split(new string[] { ":::" }, StringSplitOptions.None);
                            string   data       = string.Empty;
                            data = dicData[new Tuple <Category, Key>((Category)Enum.Parse(typeof(Category), lineValues[1]), (Key)Enum.Parse(typeof(Key), lineValues[2]))];
                            if (lineValues[0].ToString().ToUpper().Equals("Base64Unicode".ToUpper()))
                            {
                                data = TranString.EncodeBase64Unicode(data);
                            }
                            else if (lineValues[0].ToString().ToUpper().Equals("Base64Ascii".ToUpper()))
                            {
                                data = TranString.EncodeBase64(data);
                            }
                            contents.Append(lineValues[0] + ":::" + lineValues[1] + ":::" + lineValues[2] + ":::" + data + Environment.NewLine);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }


                File.WriteAllText(fullFilename, TranString.EncodeAES(contents.ToString(), key));
            }
        }
Exemple #8
0
        private void buttonGetCiphertext_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBoxKey.Text.Trim().Length == 0)
                {
                    throw new Exception("key is null. Please enter key");
                }
                if (textBoxKeyTag.Text.Trim().Length == 0)
                {
                    throw new Exception("keytag is empty. Please enter keytag");
                }

                var kmsEncrypteParameters = new
                {
                    plaintext = TranString.EncodeBase64(textBoxKey.Text)
                };
                var    jt         = JToken.Parse(JsonConvert.SerializeObject(kmsEncrypteParameters));
                string parameters = jt.ToString(Newtonsoft.Json.Formatting.Indented);

                SoaCall asyncCall = new SoaCall();
                var     response  = AsyncHelpers.RunSync <string>(() => asyncCall.WebApiCall(
                                                                      @"https://kms.apigw.ntruss.com",
                                                                      RequestType.POST,
                                                                      @"/keys/v2/" + textBoxKeyTag.Text + @"/encrypt",
                                                                      parameters,
                                                                      textBoxAccessKey.Text.Trim(),
                                                                      textBoxSecretKey.Text.Trim(), 5));

                JsonSerializerSettings options = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };

                if (!response.Contains("SUCCESS"))
                {
                    throw new Exception(response);
                }

                KmsEncryptResponse KmsEncryptResponse = JsonConvert.DeserializeObject <KmsEncryptResponse>(response, options);
                textBoxCiphertext.Text = KmsEncryptResponse.data.ciphertext;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #9
0
        private void LoadDataList2Dictionary(List <string> listName, Dictionary <Tuple <Category, Key>, string> dicName)
        {
            lock (LockObj)
            {
                dicData.Clear();
                string data = string.Empty;
                foreach (string line in listName)
                {
                    try
                    {
                        if (!line.StartsWith(@"#") && !(line == null) && !(line.Trim().Equals("")))
                        {
                            string[] lineValues = line.Split(new string[] { ":::" }, StringSplitOptions.None);

                            if (lineValues[0].ToString().Equals("Base64Unicode", StringComparison.OrdinalIgnoreCase))
                            {
                                data = TranString.DecodeBase64Unicode(lineValues[3]);
                            }
                            else if (lineValues[0].ToString().Equals("Base64Ascii", StringComparison.OrdinalIgnoreCase))
                            {
                                data = TranString.DecodeBase64(lineValues[3]);
                            }
                            else
                            {
                                data = lineValues[3];
                            }

                            dicName.Add
                            (
                                new Tuple <Category, Key>
                                (
                                    (Category)Enum.Parse(typeof(Category), lineValues[1]),
                                    (Key)Enum.Parse(typeof(Key), lineValues[2])
                                ), data
                            );
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                //var logintype = dicData[new Tuple<Category, Key>(Category.Login, Key.LoginType)];
                //LoginType = (LoginType)Enum.Parse(typeof(LoginType), logintype);
            }
        }
Exemple #10
0
        private void WriteUpdateValue2File(List <string> listName, Dictionary <Tuple <Category, Key>, string> dicName, string filename)
        {
            lock (LockObj)
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }

                using (StreamWriter file = new StreamWriter(filename))
                {
                    foreach (string line in listName)
                    {
                        try
                        {
                            if (line.StartsWith(@"#") || (line == null) || (line.Trim().Equals("")))
                            {
                                file.WriteLine(line);
                            }
                            else
                            {
                                string[] lineValues = line.Split(new string[] { ":::" }, StringSplitOptions.None);
                                string   data       = string.Empty;
                                data = dicData[new Tuple <Category, Key>((Category)Enum.Parse(typeof(Category), lineValues[1]), (Key)Enum.Parse(typeof(Key), lineValues[2]))];

                                if (lineValues[0].ToString().ToUpper().Equals("Base64Unicode".ToUpper()))
                                {
                                    data = TranString.EncodeBase64Unicode(data);
                                }
                                else if (lineValues[0].ToString().ToUpper().Equals("Base64Ascii".ToUpper()))
                                {
                                    data = TranString.EncodeBase64(data);
                                }

                                file.WriteLine(lineValues[0] + ":::" + lineValues[1] + ":::" + lineValues[2] + ":::" + data);
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                }
            }
        }
Exemple #11
0
        public async Task <string> Execute(string cmd, string cmdType, string cmdText, CsLib.RequestType type, string endPoint, string action, string accessKey, string secretKey, int timeoutSec = 0)
        {
            var json = new
            {
                cmd     = cmd,
                cmdType = cmdType,
                cmdText = TranString.EncodeBase64Unicode(cmdText)
            };

            string responseString = string.Empty;

            try
            {
                string        jsonCmd  = JsonConvert.SerializeObject(json);
                Task <string> response = new SoaCall().WebApiCall(
                    endPoint,
                    type,
                    action,
                    jsonCmd,
                    accessKey,
                    secretKey,
                    timeoutSec
                    );
                string temp = await response;
                if (temp.Length > 0)
                {
                    JToken jt = JToken.Parse(temp);
                    responseString = jt.ToString(Newtonsoft.Json.Formatting.Indented);
                }
                else
                {
                    responseString = "response is empty...";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(responseString);
        }
Exemple #12
0
        private string GetRandomKey()
        {
            string key = string.Empty;

            if (!File.Exists(encryptionKeyFullFilename))
            {
                // create key file
                int randomKey = new Random().Next(1, 100000);
                key = TranString.EncodeBase64Unicode(randomKey.ToString());
                File.WriteAllText(encryptionKeyFullFilename, key, Encoding.Default);
                key = ("0123456789012345" + key);
                key = key.Substring(key.Length - 16);
            }
            else
            {
                // read key file
                key = File.ReadAllText(encryptionKeyFullFilename, Encoding.Default);
                //string InitFile = File.ReadAllText(dataManagerContentsInitFullFilename, Encoding.Default);
                key = ("0123456789012345" + key);
                key = key.Substring(key.Length - 16);
            }
            return(key);
        }
Exemple #13
0
        private SqlServerLicenseData GetSqlServerLicenseData(string serverName)
        {
            string batchRequestsPerSec = "";
            string onlineDbCnt         = "";
            string cpuCnt           = "";
            string hyperthreadRatio = "";
            string physicalMemoryKb = "";

            SqlServerLicenseData sld = new SqlServerLicenseData();

            try
            {
                AsyncHelpers.RunSync(() => fileDb.ReadTable(FileDb.TableName.TBL_SERVER));
                TBL_SERVER_VALUE tbl_server_value = new TBL_SERVER_VALUE();
                if (fileDb.TBL_SERVER.Data.ContainsKey(new TBL_SERVER_KEY {
                    serverName = serverName
                }))
                {
                    tbl_server_value = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                                  serverName = serverName
                                                              }];
                }

                string connString = string.Empty;

                if (tbl_server_value != null)
                {
                    try
                    {
                        string decryptedPassword = TranString.DecodeRijndael(
                            tbl_server_value.serverPassword,
                            LogClient.Config.Instance.GetCryptionKey());

                        connString = new SqlConnectionStringBuilder
                        {
                            DataSource     = tbl_server_value.serverPublicIp + "," + tbl_server_value.serverPort,
                            UserID         = tbl_server_value.serverUserId,
                            Password       = decryptedPassword,
                            InitialCatalog = "master",
                            ConnectTimeout = 5,
                        }.ConnectionString;

                        using (SqlConnection conn = new SqlConnection(connString))
                        {
                            conn.Open();
                            using (SqlCommand cmd = conn.CreateCommand())
                            {
                                cmd.CommandType = System.Data.CommandType.Text;
                                cmd.CommandText =
                                    @"
set nocount on 
set transaction isolation level read uncommitted 
declare @pre int, @post int, @BatchRequestsPerSec int, @OnlineDbCnt int, @CpuCnt int, @HyperthreadRatio int, @PhysicalMemoryKb int
begin try 
    select @CpuCnt = cpu_count, @HyperthreadRatio = hyperthread_ratio, @PhysicalMemoryKb = physical_memory_kb from [sys].[dm_os_sys_info]
    select @OnlineDbCnt = count(*) from sys.databases where name not in ('master', 'tempdb', 'model', 'msdb', 'LazyLog') and state_desc = 'ONLINE'
    select @pre = cntr_value from sys.dm_os_performance_counters WHERE counter_name  ='Batch Requests/sec'
    waitfor delay '00:00:01.000'
    select @post = cntr_value from sys.dm_os_performance_counters WHERE counter_name  ='Batch Requests/sec'
    select @BatchRequestsPerSec = (@post - @pre)
end try 
begin catch 
end catch 
select 
    cast(@BatchRequestsPerSec as varchar(100)) batchRequestsPerSec 
    , cast(@OnlineDbCnt as varchar(100)) onlineDbCnt
    , cast(@CpuCnt as varchar(100)) cpuCnt
    , cast(@HyperthreadRatio as varchar(100)) hyperthreadRatio
    , cast(@PhysicalMemoryKb as varchar(100)) physicalMemoryKb
";
                                cmd.CommandTimeout = 5;
                                SqlDataReader reader = cmd.ExecuteReader();
                                while (reader.Read())
                                {
                                    batchRequestsPerSec = config.DatabaseValue <string>(reader["batchRequestsPerSec"]);
                                    onlineDbCnt         = config.DatabaseValue <string>(reader["onlineDbCnt"]);
                                    cpuCnt           = config.DatabaseValue <string>(reader["cpuCnt"]);
                                    hyperthreadRatio = config.DatabaseValue <string>(reader["hyperthreadRatio"]);
                                    physicalMemoryKb = config.DatabaseValue <string>(reader["physicalMemoryKb"]);
                                }
                                reader.Close();
                            }
                            conn.Close();
                        }

                        GetClusterInfo(GetServerName(), out string loadBalancerInstanceNo, out string serverInstanceNo, out string clusterName, out string publicIp, out string privateIp, out string serverRole);

                        sld.loadBalancerInstanceNo   = loadBalancerInstanceNo;
                        sld.loadBalancerInstanceName = clusterName;
                        sld.serverName          = serverName;
                        sld.serverInstanceNo    = serverInstanceNo;
                        sld.privateIp           = privateIp;
                        sld.serverRole          = serverRole;
                        sld.batchRequestsPerSec = batchRequestsPerSec;
                        sld.onlineDbCnt         = onlineDbCnt;
                        sld.cpuCnt           = cpuCnt;
                        sld.hyperthreadRatio = hyperthreadRatio;
                        sld.physicalMemoryKb = physicalMemoryKb;
                    }
                    catch (Exception ex)
                    {
                        log.Error(string.Format("get licensedata error {0}, {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(string.Format("{0}, {1}", ex.Message, ex.StackTrace));
            }
            return(sld);
        }
Exemple #14
0
        private async Task <WcfResponse> SqlConnectionStringSetting(string publicIp)
        {
            await Execute(@"$FileName = 'c:\temp\lazylog.mdf'
if (Test-Path $FileName) {
  Remove-Item $FileName -Force
}", publicIp);
            await Execute(@"$FileName = 'c:\temp\lazylog_log.ldf'
if (Test-Path $FileName) {
  Remove-Item $FileName -Force
}", publicIp);

            WcfResponse   wcfResponse = new WcfResponse();
            Task <string> taskString;
            string        response = string.Empty;

            var TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "GetCryptionKey",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.GetCryptionKey)
            };

            var    jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            string command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }

            // start
            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "GetCryptionKeyUrl",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.GetCryptionKeyUrl)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }
            // end



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "KeyTag",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.KeyTag)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "Ciphertext",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.Ciphertext)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeConfigSetting = new
            {
                ConfigFile = "LogClientConfig.txt",
                Category   = "Encryption",
                Key        = "LocalCryptionKey",
                Value      = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.LocalCryptionKey)
            };

            jt      = JToken.Parse(JsonConvert.SerializeObject(TypeConfigSetting));
            command = jt.ToString(Newtonsoft.Json.Formatting.Indented);

            taskString = dataManager.Execute
                             ("ExecuterRest"
                             , "TypeConfigSetting"
                             , command
                             , CsLib.RequestType.POST
                             , $"https://{publicIp}:9090"
                             , @"/LazyServer/LazyCommand/PostCmd"
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                             , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey)
                             , 60);

            response    = await taskString;
            wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);

            if (!wcfResponse.IsSuccess)
            {
                MessageBox.Show(wcfResponse.ResultMessage + wcfResponse.ErrorMessage);
            }



            TypeSqlIdPassSetting typeSqlIdPassSetting = new TypeSqlIdPassSetting
            {
                SqlId = textBoxId.Text,
                SqlEncryptedPassword = TranString.EncodeRijndael(textBoxPassword.Text, LogClient.Config.Instance.GetCryptionKey()),
                SqlDataSource        = ".",
                SqlConnectTimeout    = "5"
            };

            string cmdText        = JsonConvert.SerializeObject(typeSqlIdPassSetting);
            string responseString = string.Empty;

            try
            {
                var task = dataManager.Execute
                               ("ExecuterRest"
                               , "TypeSqlIdPassSetting"
                               , cmdText
                               , CsLib.RequestType.POST
                               , $"https://{publicIp}:9090"
                               , @"/LazyServer/LazyCommand/PostCmd"
                               , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey)
                               , LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey));

                response    = await task;
                wcfResponse = JsonConvert.DeserializeObject <WcfResponse>(response);
            }
            catch (Exception)
            {
                throw;
            }
            return(wcfResponse);
        }
Exemple #15
0
        public string GetCryptionKey(string getCryptionKey, string getCryptionKeyUrl, string accessKey, string SecretKey)
        {
            if (getCryptionKey.Equals("Local", StringComparison.OrdinalIgnoreCase))
            {
                return(GetValue(Category.Encryption, Key.LocalCryptionKey));
            }
            else if (getCryptionKey.Equals("NcpKms", StringComparison.OrdinalIgnoreCase))
            {
                for (int i = 0; i <= 3; i++)
                {
                    try
                    {
                        string _keytag     = GetValue(Category.Encryption, Key.KeyTag).Trim();
                        string _ciphertext = GetValue(Category.Encryption, Key.Ciphertext).Trim();

                        if (_keytag.Length == 0)
                        {
                            throw new Exception("keytag is empty. Please enter keytag");
                        }
                        if (_ciphertext.Length == 0)
                        {
                            throw new Exception("ciphertext is empty. Please enter ciphertext");
                        }

                        var kmsDecrypteParameters = new
                        {
                            ciphertext = _ciphertext
                        };
                        var    jt         = JToken.Parse(JsonConvert.SerializeObject(kmsDecrypteParameters));
                        string parameters = jt.ToString(Newtonsoft.Json.Formatting.Indented);

                        SoaCall asyncCall = new SoaCall();
                        var     response  = AsyncHelpers.RunSync <string>(() => asyncCall.WebApiCall(
                                                                              @"https://kms.apigw.ntruss.com",
                                                                              RequestType.POST,
                                                                              @"/keys/v2/" + _keytag + @"/decrypt",
                                                                              parameters,
                                                                              GetValue(Category.Api, Key.AccessKey),
                                                                              GetValue(Category.Api, Key.SecretKey), 5));

                        JsonSerializerSettings options = new JsonSerializerSettings
                        {
                            NullValueHandling     = NullValueHandling.Ignore,
                            MissingMemberHandling = MissingMemberHandling.Ignore
                        };

                        if (!response.Contains("SUCCESS"))
                        {
                            throw new Exception(response);
                        }

                        KmsDecryptResponse KmsDecryptResponse = JsonConvert.DeserializeObject <KmsDecryptResponse>(response, options);
                        return(TranString.DecodeBase64(KmsDecryptResponse.data.plaintext));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"ncpkms not ready!, Message : {ex.Message}");
                    }
                    Thread.Sleep(2000);
                }
            }
            else // (getCryptionKey.Equals("RemoteKeyServer", StringComparison.OrdinalIgnoreCase))
            {
                for (int i = 0; i <= 3; i++)
                {
                    try
                    {
                        SoaCall asyncCall = new SoaCall();

                        var key = AsyncHelpers.RunSync <string>(() => asyncCall.WebApiCall(
                                                                    GetValue(Category.Encryption, Key.GetCryptionKeyUrl),
                                                                    RequestType.GET,
                                                                    @"/Api/GetCryptionKey",
                                                                    GetValue(Category.Api, Key.AccessKey),
                                                                    GetValue(Category.Api, Key.SecretKey), 5));

                        key = TranString.DecodeBase64((key.Replace("\"", "")));

                        return(key);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"KeyServer not ready!, Message : {ex.Message}");
                    }
                    Thread.Sleep(2000);
                }
            }
            throw new Exception("GET KEY ERROR");
        }
Exemple #16
0
 private async Task DbSave()
 {
     try
     {
         foreach (DataGridViewRow item in dgvServerList.Rows)
         {
             if (bool.Parse(item.Cells["CheckBox"].Value.ToString()))
             {
                 string publicIp = item.Cells["PublicIp"].Value.ToString();
                 if (publicIp == null && publicIp.Length == 0)
                 {
                     throw new Exception("publicip is null");
                 }
                 else
                 {
                     var p = new List <KeyValuePair <string, string> >();
                     p.Add(new KeyValuePair <string, string>("serverName", item.Cells["Name"].Value.ToString()));
                     p.Add(new KeyValuePair <string, string>("serverInstanceNo", item.Cells["InstanceNo"].Value.ToString()));
                     p.Add(new KeyValuePair <string, string>("serverPublicIp", item.Cells["PublicIp"].Value.ToString()));
                     p.Add(new KeyValuePair <string, string>("serverPrivateIp", item.Cells["PrivateIp"].Value.ToString()));
                     p.Add(new KeyValuePair <string, string>("serverPort", textBoxPort.Text.Trim()));
                     p.Add(new KeyValuePair <string, string>("serverUserId", textBoxId.Text.Trim()));
                     p.Add(new KeyValuePair <string, string>("serverPassword", TranString.EncodeRijndael(
                                                                 textBoxPassword.Text.Trim(),
                                                                 LogClient.Config.Instance.GetCryptionKey()
                                                                 )));
                     await fileDb.UpSertTable(FileDb.TableName.TBL_SERVER, p);
                 }
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemple #17
0
            public WcfResponse PostLazyCommand(LazyCommand lazyCommand)
            {
                WcfResponse wcfResponse;
                string      cmdText = string.Empty;

                try
                {
                    cmdText = TranString.DecodeBase64Unicode(lazyCommand.cmdText);
                }
                catch (Exception)
                {
                    cmdText = lazyCommand.cmdText;
                }

                if (new BasicAuthentication(WebOperationContext.Current.IncomingRequest).AuthSuccess())
                {
                    string result = string.Empty;

                    if (!HasCriticalString(lazyCommand.cmdType) && !HasCriticalString(lazyCommand.cmdText) && !HasCriticalString(cmdText))
                    {
                        log.Warn(string.Format("pre logging, {0}, {1}, {2}", lazyCommand.cmdType, lazyCommand.cmdText, cmdText));
                    }
                    else
                    {
                        log.Warn(string.Format("pre logging, string has critical word, skipped log."));
                    }

                    if (lazyCommand.cmd.Equals("ExecuterPs", StringComparison.OrdinalIgnoreCase)) // sync
                    {
                        return(new ExecuterPs(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeKeySetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeSqlIdPassSetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeConfigSetting", StringComparison.OrdinalIgnoreCase) ||
                             lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeConfigRead", StringComparison.OrdinalIgnoreCase)
                             )
                    {
                        return(new KeyManager(lazyCommand.cmdType).Execute(cmdText, true)); // TypeKeySetting, ChangeKeySetting, Auth Success, TypeConfigSetting
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new ExecuterRest(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else if (lazyCommand.cmd.Equals("ExecuterSql", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new ExecuterSql(lazyCommand.cmdType).Execute(cmdText));
                    }
                    else
                    {
                        return(new WcfResponse
                        {
                            IsSuccess = false,
                            ResultMessage = "",
                            ErrorMessage = "unknown cmd"
                        });
                    }
                }
                else // auth fail
                {
                    if (lazyCommand.cmd.Equals("ExecuterRest", StringComparison.OrdinalIgnoreCase) && lazyCommand.cmdType.Equals("TypeKeySetting", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new KeyManager(lazyCommand.cmdType).Execute(cmdText, false)); //TypeKeySetting, FirstKeySetting, Auth Fail
                    }
                    log.Warn("PASS FAIL");
                    wcfResponse = new WcfResponse
                    {
                        IsSuccess     = false,
                        ResultMessage = "",
                        ErrorMessage  = "Authentication Failed"
                    };
                }

                return(wcfResponse);
            }
Exemple #18
0
        private void CheckConfigurationKey()
        {
            AppendVerifyLog("*. Encrytpion Key");

            string getCryptionKeyType = logClientConfig.GetValue(LogClient.Category.Encryption, LogClient.Key.GetCryptionKey);
            string keyTag             = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.KeyTag);
            string ciphertext         = LogClient.Config.Instance.GetValue(LogClient.Category.Encryption, LogClient.Key.Ciphertext);

            try
            {
                AppendVerifyLog($"   Current Encrytpion Type : {getCryptionKeyType}");
                if (getCryptionKeyType.Equals("Local", StringComparison.OrdinalIgnoreCase))
                {
                    AppendVerifyLog("   Cryption Key : " + logClientConfig.GetValue(Category.Encryption, Key.LocalCryptionKey));
                    if (logClientConfig.GetValue(Category.Encryption, Key.LocalCryptionKey).Length == 0)
                    {
                        AppendVerifyLog($"   [Warning] Cryption Key is too short! (key length is : {logClientConfig.GetValue(Category.Encryption, Key.LocalCryptionKey).Length})");
                    }
                }
                else
                {
                    if (keyTag.Length <= 1)
                    {
                        throw new Exception("   [ERROR] The KMS keytag is not corrent!");
                    }

                    if (ciphertext.Length <= 1)
                    {
                        throw new Exception("   [ERROR] The KMS ciphertext is not corrent!");
                    }

                    var kmsDecrypteParameters = new
                    {
                        ciphertext = ciphertext
                    };
                    var    jt         = JToken.Parse(JsonConvert.SerializeObject(kmsDecrypteParameters));
                    string parameters = jt.ToString(Newtonsoft.Json.Formatting.Indented);

                    SoaCall asyncCall = new SoaCall();
                    var     response  = AsyncHelpers.RunSync <string>(() => asyncCall.WebApiCall(
                                                                          @"https://kms.apigw.ntruss.com",
                                                                          RequestType.POST,
                                                                          @"/keys/v2/" + keyTag + @"/decrypt",
                                                                          parameters,
                                                                          LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.AccessKey),
                                                                          LogClient.Config.Instance.GetValue(LogClient.Category.Api, LogClient.Key.SecretKey), 5));

                    JsonSerializerSettings options = new JsonSerializerSettings
                    {
                        NullValueHandling     = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };

                    if (!response.Contains("SUCCESS"))
                    {
                        throw new Exception(response);
                    }

                    KmsDecryptResponse KmsDecryptResponse = JsonConvert.DeserializeObject <KmsDecryptResponse>(response, options);
                    AppendVerifyLog("   Cryption KMS key : " + TranString.DecodeBase64(KmsDecryptResponse.data.plaintext));
                }

                AppendVerifyLog($"   Encryption Key Check Result : Success");
            }
            catch (Exception ex)
            {
                AppendVerifyLog(ex.Message);
                AppendVerifyLog("   Encryption Key(KMS) Help Message...");
                AppendVerifyLog("   -----------------------------------------------");
                AppendVerifyLog("   1. Enable subaccount in MC Console.");
                AppendVerifyLog("   2. In the Management Console, create a key for encryption / decryption.");
                AppendVerifyLog("   3. Paste the generated keytag into the SQL Server DBA Tool.");
                AppendVerifyLog("   4. In the SQL Server DBA Tool, type key");
                AppendVerifyLog("   5. Create ciphertext in the SQL Server DBA Tool.");
                AppendVerifyLog("   6. Save.");
                AppendVerifyLog("   -----------------------------------------------");
                throw new Exception("Encryption Key Error!");
            }
        }
Exemple #19
0
        private bool QueryExecuter(string listStringQuery, int commandTimeout = 30)
        {
            bool bReturn = false;

            sbResultAll.Clear();
            List <string> querys = TranString.ReadQuery(listStringQuery);

            startTime = DateTime.Now;

            foreach (var query in querys)
            {
                try
                {
                    if (CancelRequested)
                    {
                        break;
                    }

                    sbResultAll.Append("-->>---------------------------------");
                    sbResultAll.Append(query + Environment.NewLine);
                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);
                    if (query.Trim().ToUpper().StartsWith("USE"))
                    {
                        string[] database = query.Trim().Split(new[] { Environment.NewLine, " " }, StringSplitOptions.None);
                        ConnectionString = SetConnectionString(database[1]);
                    }
                    string result = string.Empty;


                    using (SqlConnection conn = new SqlConnection(ConnectionString))
                    {
                        conn.Open();
                        conn.InfoMessage += Conn_InfoMessage; // message hook (like backup message)


                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.StatementCompleted += Cmd_StatementCompleted; // retrive row count

                            cmd.CommandType = CommandType.Text;

                            //// execute only estimation plan text
                            //cmd.CommandText = "SET SHOWPLAN_ALL ON";
                            //cmd.ExecuteNonQuery();

                            //// execute only estimation plan xml
                            //cmd.CommandText = "SET SHOWPLAN_XML ON";
                            //cmd.ExecuteNonQuery();

                            cmd.CommandText = query;
                            SqlDataReader reader = cmd.ExecuteReader();

                            do
                            {
                                StringBuilder sb          = new StringBuilder();
                                string        Header      = string.Empty;
                                string        Line        = string.Empty;
                                DataTable     schemaTable = reader.GetSchemaTable();
                                if (schemaTable != null)
                                {
                                    try
                                    {
                                        foreach (DataRow row in schemaTable.Rows)
                                        {
                                            foreach (DataColumn column in schemaTable.Columns)
                                            {
                                                if (column.ColumnName == "ColumnName")
                                                {
                                                    Header = Header + row[column] + ColumnDelimiter;
                                                }
                                            }
                                        }
                                        Header = Header + Environment.NewLine;
//                                        Line = Line + Environment.NewLine;
                                        sb.Append(Header);
                                        sb.Append(Line);

                                        while (reader.Read())
                                        {
                                            for (int i = 0; i < reader.FieldCount; i++)
                                            {
                                                if (reader.GetValue(i).ToString() == "System.Byte[]")
                                                {
                                                    sb.Append("0x" + BitConverter.ToString((byte[])reader.GetValue(i)).Replace("-", ""));
                                                }
                                                else
                                                {
                                                    sb.Append(reader.GetValue(i).ToString());
                                                }
                                                sb.Append(ColumnDelimiter);
                                            }
                                            sb.Append(Environment.NewLine);
                                        }
                                    }
                                    catch (SqlException ex)
                                    {
                                        ErrorCnt++;
                                        sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                                        sbResultAll.Append("--SQL Exception" + Environment.NewLine);
                                        sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                                        for (int i = 0; i < ex.Errors.Count; i++)
                                        {
                                            sbResultAll.Append("Inner SqlException No #" + i + Environment.NewLine +
                                                               "Message: " + ex.Errors[i].Message + Environment.NewLine +
                                                               "Source: " + ex.Errors[i].Source + Environment.NewLine +
                                                               "Procedure: " + ex.Errors[i].Procedure + Environment.NewLine);
                                        }
                                    }
                                    finally
                                    {
                                        sb.Append(Environment.NewLine);
                                        sbResultAll.Append(sb);
                                        sbResultAll.Append(string.Format("({0} {1} affected)" + Environment.NewLine + Environment.NewLine, recordCount, (recordCount == 1) ? "row" : "rows"));
                                    }
                                }
                                else
                                {
                                    string[] Query = query.Trim().Split(new[] { Environment.NewLine, " " }, StringSplitOptions.None);
                                    if (
                                        Query[0].Equals("update", StringComparison.OrdinalIgnoreCase) ||
                                        Query[0].Equals("insert", StringComparison.OrdinalIgnoreCase) ||
                                        Query[0].Equals("delete", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("update", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("insert", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("delete", StringComparison.OrdinalIgnoreCase)
                                        )
                                    {
                                        sbResultAll.Append(string.Format("({0} {1} affected)" + Environment.NewLine + Environment.NewLine, recordCount, (recordCount == 1) ? "row" : "rows"));
                                    }
                                    else
                                    {
                                        sbResultAll.Append(string.Format("Commands completed successfully." + Environment.NewLine + Environment.NewLine));
                                    }
                                }
                            } while (reader.NextResult());
                        }
                        conn.Close();
                        bReturn = true;
                    }
                }

                catch (SqlException ex)
                {
                    ErrorCnt++;
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append("--SQL Exception" + Environment.NewLine);
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);

                    for (int i = 0; i < ex.Errors.Count; i++)
                    {
                        sbResultAll.Append("SqlException No #" + i + Environment.NewLine +
                                           "Message: " + ex.Errors[i].Message + Environment.NewLine +
                                           "Source: " + ex.Errors[i].Source + Environment.NewLine +
                                           "Procedure: " + ex.Errors[i].Procedure + Environment.NewLine);
                    }

                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);

                    bReturn = false;
                }
                catch (Exception ex)
                {
                    ErrorCnt++;
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append("--Exception" + Environment.NewLine);
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append(ex.Message);
                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);
                    bReturn = false;
                }
            }

            //sbResultAll.Append(Environment.NewLine + "-->>---------------------------------" + Environment.NewLine);
            endTime = DateTime.Now;
            //sbResultAll.Append("EndTime : " + endTime.ToString("yyyy-MM-dd HH:mm:ss.fff") + Environment.NewLine);
            sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);
            sbResultAll.Append(Environment.NewLine + "-->>---------------------------------" + Environment.NewLine);
            sbResultAll.Append("StartTime : " + startTime.ToString("yyyy-MM-dd HH:mm:ss.fff") + Environment.NewLine);
            sbResultAll.Append("EndTime : " + endTime.ToString("yyyy-MM-dd HH:mm:ss.fff") + Environment.NewLine);
            TimeSpan diff      = endTime - startTime;
            string   formatted = string.Format(
                "TotalExecutionTime : {0} days, {1} hours, {2} minutes, {3} seconds, {4} miliseconds",
                diff.Days,
                diff.Hours,
                diff.Minutes,
                diff.Seconds,
                diff.Milliseconds
                );

            sbResultAll.Append(formatted + Environment.NewLine);
            sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);

            return(bReturn);
        }
Exemple #20
0
        public Config()
        {
            logClientConfig = LogClient.Config.Instance;
            logClientConfig.SqlPasswordChangedEvent += UpdateEncryptedSqlPassword;
            while (!logClientConfig.KeySettingCompleted())
            {
                Thread.Sleep(2000);
                Console.WriteLine("Wait For AccessKey and SecretKey");
            }
            listData = new List <string>();
            dicData  = new Dictionary <Tuple <Category, Key>, string>();

            dataSettingFullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dataSettingFileName);
            LoadFile2List(dataSettingFullName, listData);
            LoadDataList2Dictionary(listData, dicData);
            ConfigLoaded = true;


            while (true)
            {
                if (!logClientConfig.SqlIdPassordSettingCompleted())
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("Wait For SqlId SqlPass");
                }
                else
                {
                    try
                    {
                        if (!LogClient.Config.Instance.GetValue(LogClient.Category.Repository, LogClient.Key.SqlEncryptedPassword).Trim().Equals(""))
                        {
                            DecryptedPassword = TranString.DecodeRijndael(
                                LogClient.Config.Instance.GetValue(LogClient.Category.Repository, LogClient.Key.SqlEncryptedPassword),
                                LogClient.Config.Instance.GetCryptionKey());
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        log.Error(string.Format("Cryption Error : {0}, {1}", ex.Message, ex.StackTrace));
                        Thread.Sleep(2000);
                    }
                }
            }

            // Sender:::Type:::B     ncp
            if (GetValue(Category.Sender, Key.Type).Equals("b", StringComparison.OrdinalIgnoreCase))
            {
                log.Error("Database Create Skipped Sender:::Type:::B");
                DbConfigLoad();
                log.Error("database configuration load completed!");
            }
            else
            {
                //// schema gen
                CounterLoaded = false;
                if (IsExistsRepository(GetValue(Category.Repository, Key.InitialCatalog)))
                {
                    log.Warn("Database Create Skipped");
                }
                else
                {
                    try
                    {
                        if (!Directory.Exists(GetValue(Category.Repository, Key.DatabaseFilePath)))
                        {
                            Directory.CreateDirectory(GetValue(Category.Repository, Key.DatabaseFilePath));
                        }
                        if (!Directory.Exists(GetValue(Category.Repository, Key.LogFilePath)))
                        {
                            Directory.CreateDirectory(GetValue(Category.Repository, Key.LogFilePath));
                        }

                        if (Common.QueryExecuter(GetConnectionString(InitialCatalog.Master)
                                                 , string.Format(CreateRepositoryQuery,
                                                                 GetValue(Category.Repository, Key.InitialCatalog),
                                                                 GetValue(Category.Repository, Key.DatabaseFilePath),
                                                                 GetValue(Category.Repository, Key.LogFilePath))))
                        {
                            log.Warn("Database Create Success");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(string.Format("{0}, {1}", ex.Message, ex.StackTrace));
                    }
                }
            }

            try
            {
                CounterLoaded = IsExistsCounterDetails();

                if (GetValue(Category.Perfmon, Key.SkipLoadCounter).ToUpper() == "Y" && CounterLoaded)
                {
                    log.Warn("Schema Create Skipped");
                }
                else
                {
                    if (Common.QueryExecuter(GetConnectionString(InitialCatalog.Repository), CreateSchemaQuery))
                    {
                        log.Warn("Schema Create Success");
                    }
                    else
                    {
                        log.Warn("Schema Create Failed");
                    }
                }
                //// schema gen completed

                LocalIp   = Common.GetLocalIpAddress(IpType.LocalFirstIp);
                LocalPort = GetPort();
                SetSqlVersion();
            }
            catch (Exception ex)
            {
                log.Error(string.Format("{0}, {1}", ex.Message, ex.StackTrace));
            }
        }
Exemple #21
0
 private void ComboBoxScriptTemplatesChanged(object sender, EventArgs e)
 {
     fastColoredTextBoxTemplate.Text = TranString.DecodeBase64Unicode(templateManager.Templates[comboBoxScriptTemplates.SelectedItem.ToString()]);
 }
Exemple #22
0
        public async Task <bool> LastConnectionTest(string serverName)
        {
            bool returnValue = false;
            await fileDb.ReadTable(FileDb.TableName.TBL_SERVER);

            TBL_SERVER_VALUE tbl_server_value = new TBL_SERVER_VALUE();

            if (fileDb.TBL_SERVER.Data.ContainsKey(new TBL_SERVER_KEY {
                serverName = serverName
            }))
            {
                tbl_server_value = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                              serverName = serverName
                                                          }];
            }

            string connString = string.Empty;

            if (tbl_server_value != null)
            {
                try
                {
                    string decryptedPassword = TranString.DecodeRijndael(
                        tbl_server_value.serverPassword,
                        LogClient.Config.Instance.GetCryptionKey());

                    connString = new SqlConnectionStringBuilder
                    {
                        DataSource     = tbl_server_value.serverPublicIp + "," + tbl_server_value.serverPort,
                        UserID         = tbl_server_value.serverUserId,
                        Password       = decryptedPassword,
                        InitialCatalog = "master",
                        ConnectTimeout = 5,
                    }.ConnectionString;

                    using (SqlConnection conn = new SqlConnection(connString))
                    {
                        conn.Open();
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandType    = System.Data.CommandType.Text;
                            cmd.CommandText    = @"select top 1 'normal' as healthStatus";
                            cmd.CommandTimeout = 5;
                            SqlDataReader reader = cmd.ExecuteReader();
                            while (reader.Read())
                            {
                                config.DatabaseValue <string>(reader["healthStatus"]);
                            }
                            reader.Close();
                            returnValue = true;
                        }
                        conn.Close();
                        log.Warn("last connection test success!");
                    }
                }
                catch (Exception ex)
                {
                    log.Error(string.Format("{0}, {1}", ex.Message, ex.StackTrace));
                }
            }
            return(returnValue);
        }
Exemple #23
0
 private void UpdateEncryptedSqlPassword(object sender, SqlPasswordArgs e)
 {
     DecryptedPassword = TranString.DecodeRijndael(e.SqlEncryptedPassword, LogClient.Config.Instance.GetCryptionKey());
 }
Exemple #24
0
        private bool QueryExecuter(string listStringQuery, int commandTimeout = 30)
        {
            bool bReturn = false;

            sbResultAll.Clear();
            List <string> querys = TranString.ReadQuery(listStringQuery);

            sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
            sbResultAll.Append(DateTime.Now + Environment.NewLine);
            sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);

            foreach (var query in querys)
            {
                try
                {
                    sbResultAll.Append("-->>---------------------------------");
                    sbResultAll.Append(query + Environment.NewLine);
                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);
                    if (query.Trim().ToUpper().StartsWith("USE"))
                    {
                        string[] database = query.Trim().Split(new[] { Environment.NewLine, " " }, StringSplitOptions.None);
                        connectionString = SetConnectionString(database[1]);
                        comboBoxDatabase.InvokeIfRequired(s =>
                        {
                            s.Text         = "";
                            s.SelectedText = database[1].ToString();
                        });
                    }
                    string result = string.Empty;
                    using (SqlConnection conn = new SqlConnection(connectionString))
                    {
                        conn.Open();
                        conn.InfoMessage += Conn_InfoMessage; // message hook (like backup message)

                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.StatementCompleted += Cmd_StatementCompleted; // retrive row count
                            cmd.CommandType         = CommandType.Text;
                            cmd.CommandText         = query;
                            cmd.CommandTimeout      = commandTimeout;
                            SqlDataReader reader          = cmd.ExecuteReader();
                            int           recordsAffected = reader.RecordsAffected;

                            do
                            {
                                StringBuilder sb          = new StringBuilder();
                                string        Header      = string.Empty;
                                string        Line        = string.Empty;
                                DataTable     schemaTable = reader.GetSchemaTable();
                                if (schemaTable != null)
                                {
                                    try
                                    {
                                        foreach (DataRow row in schemaTable.Rows)
                                        {
                                            foreach (DataColumn column in schemaTable.Columns)
                                            {
                                                if (column.ColumnName == "ColumnName")
                                                {
                                                    Header = Header + row[column] + "\t";
                                                    Line   = Line + "------- ";
                                                }
                                            }
                                        }
                                        Header = Header + Environment.NewLine;
                                        Line   = Line + Environment.NewLine;
                                        sb.Append(Header);
                                        sb.Append(Line);

                                        while (reader.Read())
                                        {
                                            for (int i = 0; i < reader.FieldCount; i++)
                                            {
                                                if (reader.GetValue(i).ToString() == "System.Byte[]")
                                                {
                                                    sb.Append("0x" + BitConverter.ToString((byte[])reader.GetValue(i)).Replace("-", ""));
                                                }
                                                else
                                                {
                                                    sb.Append(reader.GetValue(i).ToString());
                                                }
                                                sb.Append("\t");
                                            }
                                            sb.Append(Environment.NewLine);
                                        }
                                    }
                                    catch (SqlException ex)
                                    {
                                        errorCnt++;
                                        sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                                        sbResultAll.Append("--SQL Exception" + Environment.NewLine);
                                        sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                                        for (int i = 0; i < ex.Errors.Count; i++)
                                        {
                                            sbResultAll.Append("Inner SqlException No #" + i + Environment.NewLine +
                                                               "Message: " + ex.Errors[i].Message + Environment.NewLine +
                                                               "Source: " + ex.Errors[i].Source + Environment.NewLine +
                                                               "Procedure: " + ex.Errors[i].Procedure + Environment.NewLine);
                                        }
                                    }
                                    finally
                                    {
                                        sb.Append(Environment.NewLine);
                                        sbResultAll.Append(sb);
                                        sbResultAll.Append(string.Format("({0} {1} affected)" + Environment.NewLine + Environment.NewLine, recordCount, (recordCount == 1) ? "row" : "rows"));
                                    }
                                }
                                else
                                {
                                    string[] Query = query.Trim().Split(new[] { Environment.NewLine, " " }, StringSplitOptions.None);
                                    if (
                                        Query[0].Equals("update", StringComparison.OrdinalIgnoreCase) ||
                                        Query[0].Equals("insert", StringComparison.OrdinalIgnoreCase) ||
                                        Query[0].Equals("delete", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("update", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("insert", StringComparison.OrdinalIgnoreCase) ||
                                        Query[1].Equals("delete", StringComparison.OrdinalIgnoreCase)
                                        )
                                    {
                                        sbResultAll.Append(string.Format("({0} {1} affected)" + Environment.NewLine + Environment.NewLine, recordCount, (recordCount == 1) ? "row" : "rows"));
                                    }
                                    else
                                    {
                                        sbResultAll.Append(string.Format("Commands completed successfully." + Environment.NewLine + Environment.NewLine));
                                    }
                                }
                                reader.NextResult();
                            } while (reader.HasRows);
                        }
                        conn.Close();
                        bReturn = true;
                    }

                    if (checkBoxResultUpdateByGo.Checked)
                    {
                        fastColoredTextBoxResult.InvokeIfRequired(s =>
                        {
                            s.Text = sbResultAll.ToString();
                        });
                    }
                }

                catch (SqlException ex)
                {
                    errorCnt++;
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append("--SQL Exception" + Environment.NewLine);
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);

                    for (int i = 0; i < ex.Errors.Count; i++)
                    {
                        sbResultAll.Append("SqlException No #" + i + Environment.NewLine +
                                           "Message: " + ex.Errors[i].Message + Environment.NewLine +
                                           "Source: " + ex.Errors[i].Source + Environment.NewLine +
                                           "Procedure: " + ex.Errors[i].Procedure + Environment.NewLine);
                    }

                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);

                    if (checkBoxResultUpdateByGo.Checked)
                    {
                        fastColoredTextBoxResult.InvokeIfRequired(s =>
                        {
                            s.Text = sbResultAll.ToString();
                        });
                    }

                    bReturn = false;
                }
                catch (Exception ex)
                {
                    errorCnt++;
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append("--Exception" + Environment.NewLine);
                    sbResultAll.Append("-->>---------------------------------" + Environment.NewLine);
                    sbResultAll.Append(ex.Message);
                    sbResultAll.Append("---------------------------------<<--" + Environment.NewLine + Environment.NewLine);

                    if (checkBoxResultUpdateByGo.Checked)
                    {
                        fastColoredTextBoxResult.InvokeIfRequired(s =>
                        {
                            s.Text = sbResultAll.ToString();
                        });
                    }

                    bReturn = false;
                }
            }

            fastColoredTextBoxResult.InvokeIfRequired(s =>
            {
                s.Text = sbResultAll.ToString();
            });

            return(bReturn);
        }
Exemple #25
0
        private string GetCreateServerInstancesJsonCommand()
        {
            try
            {
                List <KeyValuePair <string, string> > listKeyValueParameters = GetParameters();
                listKeyValueParameters.Add(new KeyValuePair <string, string>("responseFormatType", "json"));
                listKeyValueParameters.Add(new KeyValuePair <string, string>("userData", TranString.EncodeBase64(dataManager.GetValue(DataManager.Category.InitScript, DataManager.Key.userDataFinal))));
                Dictionary <string, string> dicParameters = new Dictionary <string, string>();

                foreach (var a in listKeyValueParameters)
                {
                    if (a.Value == null || a.Value.Equals("NULL", StringComparison.OrdinalIgnoreCase))
                    {
                    }
                    else
                    {
                        dicParameters.Add(a.Key, a.Value);
                    }
                }
                JToken jt = JToken.Parse(JsonConvert.SerializeObject(dicParameters));
                return(jt.ToString(Newtonsoft.Json.Formatting.Indented).Replace("_", "."));
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #26
0
        private void FillConnectionInfo(string clusterName, string radioConnectionType, bool usePrivateIp)
        {                                                          // master slave domain
            try
            {
                string ip                = string.Empty;
                string port              = string.Empty;
                string userid            = string.Empty;
                string password          = string.Empty;
                string db                = "master";
                int    connectTimeoutSec = 3;
                int    commandTimeoutSec = 30;
                string masterServerName  = string.Empty;
                string slaveServerName   = string.Empty;
                string serverName        = string.Empty;

                foreach (var a in fileDb.TBL_CLUSTER_SERVER.Data)
                {
                    if (a.Key.clusterName.Equals(clusterName) && a.Value.serverRole.Equals("MASTER", StringComparison.OrdinalIgnoreCase))
                    {
                        masterServerName = a.Key.serverName;
                    }
                    else if ((a.Key.clusterName.Equals(clusterName) && a.Value.serverRole.Equals("SLAVE", StringComparison.OrdinalIgnoreCase)))
                    {
                        slaveServerName = a.Key.serverName;
                    }
                }

                serverName = radioConnectionType.Equals("SLAVE", StringComparison.OrdinalIgnoreCase) == false ? masterServerName : slaveServerName;


                if (!serverName.Equals(""))
                {
                    if (usePrivateIp)
                    {
                        ip = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                        serverName = serverName
                                                    }].serverPrivateIp;
                    }
                    else
                    {
                        ip = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                        serverName = serverName
                                                    }].serverPublicIp;
                    }

                    if (radioConnectionType.Equals("DOMAIN", StringComparison.OrdinalIgnoreCase))
                    {
                        ip = fileDb.TBL_CLUSTER.Data[new TBL_CLUSTER_KEY {
                                                         clusterName = clusterName
                                                     }].domainName;
                    }

                    port     = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                          serverName = serverName
                                                      }].serverPort;
                    userid   = fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                          serverName = serverName
                                                      }].serverUserId;
                    password = TranString.DecodeRijndael(
                        fileDb.TBL_SERVER.Data[new TBL_SERVER_KEY {
                                                   serverName = serverName
                                               }].serverPassword,
                        LogClient.Config.Instance.GetCryptionKey());

                    textBoxServerName.Text           = serverName;
                    textBoxIP.Text                   = ip;
                    textBoxPort.Text                 = port;
                    textBoxUserId.Text               = userid;
                    textBoxPassword.Text             = password;
                    textBoxConnectionTimeoutSec.Text = connectTimeoutSec.ToString();
                    textBoxCommandTimeoutSec.Text    = commandTimeoutSec.ToString();
                    comboBoxDatabase.Text            = db;
                }
                else
                {
                    textBoxServerName.Text           = "";
                    textBoxIP.Text                   = "";
                    textBoxPort.Text                 = "";
                    textBoxUserId.Text               = "";
                    textBoxPassword.Text             = "";
                    textBoxConnectionTimeoutSec.Text = "";
                    textBoxCommandTimeoutSec.Text    = "";
                    comboBoxDatabase.Text            = "";
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                throw;
            }
        }
Exemple #27
0
        private void buttonKeyTest_Click(object sender, EventArgs e)
        {
            if (radioButtonLocalKey.Checked)
            {
                MessageBox.Show(logClientConfig.GetValue(Category.Encryption, Key.LocalCryptionKey));
            }
            else //(radioButtonNcpKms.Checked)
            {
                try
                {
                    if (textBoxKeyTag.Text.Trim().Length == 0)
                    {
                        throw new Exception("keytag is empty. Please enter keytag");
                    }
                    if (textBoxCiphertext.Text.Trim().Length == 0)
                    {
                        throw new Exception("ciphertext is empty. Please enter ciphertext");
                    }

                    var kmsDecrypteParameters = new
                    {
                        ciphertext = textBoxCiphertext.Text
                    };
                    var    jt         = JToken.Parse(JsonConvert.SerializeObject(kmsDecrypteParameters));
                    string parameters = jt.ToString(Newtonsoft.Json.Formatting.Indented);

                    SoaCall asyncCall = new SoaCall();
                    var     response  = AsyncHelpers.RunSync <string>(() => asyncCall.WebApiCall(
                                                                          @"https://kms.apigw.ntruss.com",
                                                                          RequestType.POST,
                                                                          @"/keys/v2/" + textBoxKeyTag.Text + @"/decrypt",
                                                                          parameters,
                                                                          textBoxAccessKey.Text.Trim(),
                                                                          textBoxSecretKey.Text.Trim(), 5));

                    JsonSerializerSettings options = new JsonSerializerSettings
                    {
                        NullValueHandling     = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };

                    if (!response.Contains("SUCCESS"))
                    {
                        throw new Exception(response);
                    }

                    KmsDecryptResponse KmsDecryptResponse = JsonConvert.DeserializeObject <KmsDecryptResponse>(response, options);
                    MessageBox.Show(TranString.DecodeBase64(KmsDecryptResponse.data.plaintext));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            //else
            //{
            //    try
            //    {
            //        SoaCall asyncCall = new SoaCall();

            //        var key = AsyncHelpers.RunSync<string>(() => asyncCall.WebApiCall(
            //            textBoxRemoteKeyServerUrl.Text.Trim(),
            //            RequestType.GET,
            //            textBoxAction.Text.Trim(),
            //            textBoxAccessKey.Text.Trim(),
            //            textBoxSecretKey.Text.Trim(), 5));

            //        if (key.Contains("Endpoint not found."))
            //        {
            //            throw new Exception("Endpoint not found.");
            //        }
            //        key = TranString.DecodeBase64((key.Replace("\"", "")));
            //        if (key.Equals(""))
            //            MessageBox.Show("authentication error, check accessKey and secretKey");
            //        else
            //            MessageBox.Show(key);
            //    }
            //    catch (Exception ex)
            //    {
            //        if (ex.Message.Contains("A task was canceled."))
            //        {
            //            MessageBox.Show("Unable to connect to the remote server");
            //            return;
            //        }
            //        if (ex.InnerException != null)
            //        {
            //            MessageBox.Show(ex.InnerException.Message);
            //        }
            //        else
            //        {
            //            MessageBox.Show(ex.Message);
            //        }
            //    }
            //}
        }