Пример #1
0
        //void ReloadConectionGroupInfos()
        //{
        //    var filenames = _filesProvider.GetConnectionsFilenames();
        //    _connections = new List<ConnectionGroupInfo>();
        //    foreach (var filename in filenames)
        //    {
        //        _connections.AddRange(ConnectionsLoader.LoadFromXml(filename));
        //    }
        //}

        /// <summary>
        /// Load Template
        /// </summary>
        /// <param name="filename">Xml-file name</param>
        /// <param name="connectionGroup"></param>
        /// <param name="isExternal">Is opened from user file template</param>
        /// <returns>Tree template</returns>
        public TemplateNodeInfo LoadTemplateNodes(
            string filename,
            bool isExternal,
            out string startupTemplateId,
            out Stack <string> startupTemplateInfoIdStack
            )
        {
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("Template needed!");
            }

            var doc = new XmlDocument();

            doc.Load(filename);

            if (AppVersionHelper.IsNotDebug() && !isExternal)
            {
                var cryptoProcessor = new CryptoProcessor(
                    this.Settings.SystemSettings.PublicKeyXmlSign,
                    this.Settings.SystemSettings.PrivateKeyXmlDecrypt
                    );

                cryptoProcessor.DecryptXmlDocument(doc);
            }

            return(TemplateNodesLoader.LoadFromXml(this, doc, out startupTemplateId, out startupTemplateInfoIdStack));
        }
        public static void SetDatabaseFileInformation(string databaseStorageLocation, string databaseDatabaseFileName, string databaseKeyFileName, string databasePassword)
        {
            SetDatabaseFileInformation(databaseStorageLocation, databaseDatabaseFileName, databaseKeyFileName);
            string encryptedPassword = CryptoProcessor.Encrypt(databasePassword);

            SetDatabaseMasterPassword(null, encryptedPassword);
        }
        public static void SetDatabaseMasterPassword(SecureString password = null, string encryptedTextPassword = "")
        {
            if (password != null)
            {
                DatabaseInfo.DatabaseMasterPassword = password;
            }

            if (!string.IsNullOrWhiteSpace(encryptedTextPassword))
            {
                string unencryptedPassword = CryptoProcessor.Decrypt(encryptedTextPassword);
                if (string.IsNullOrWhiteSpace(unencryptedPassword))
                {
                    throw new ArgumentException("Encrypted Text Failed to decrypt. Please Reset the Password and update storage");
                }
                SecureString secureStringPassword = new SecureString();
                foreach (char c in unencryptedPassword)
                {
                    secureStringPassword.AppendChar(c);
                }

                if (password != null)
                {
                    if (password.GetHashCode() != secureStringPassword.GetHashCode())
                    {
                        throw new ArgumentException("You can only pass one password type, please remove one password from the method call and try again.");
                    }
                }
                else
                {
                    DatabaseInfo.DatabaseMasterPassword = secureStringPassword;
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Decrypts an encrypted private key.
        /// </summary>
        /// <param name="privateKey">The encrypted private key.</param>
        /// <param name="password">The matching password.</param>
        /// <returns>The decrypted private key.</returns>
        public static async Task <byte[]> DecryptPrivateKeyAsync(this byte[] privateKey, string password)
        {
            await using var inputStream  = new MemoryStream(privateKey);
            await using var outputStream = new MemoryStream();
            await CryptoProcessor.Decrypt(inputStream, outputStream, password);

            return(outputStream.ToArray());
        }
Пример #5
0
        /// <summary>
        /// Decrypts an encrypted private key.
        /// </summary>
        /// <param name="privateKey">The encrypted private key.</param>
        /// <param name="password">The matching password.</param>
        /// <returns>The decrypted private key.</returns>
        public static ReadOnlySpan <byte> DecryptPrivateKey(this ReadOnlySpan <byte> privateKey, string password)
        {
            using var inputStream  = new MemoryStream(privateKey.ToArray());
            using var outputStream = new MemoryStream();
            CryptoProcessor.Decrypt(inputStream, outputStream, password).Wait();

            return(outputStream.ToArray());
        }
Пример #6
0
        public async Task TestTooShortPassword4Decryption()
        {
            var message  = "This is a test with umlauts äüö.";
            var password = "******";

            var encryptedData = await CryptoProcessor.Encrypt(message, password);

            try
            {
                var decryptedMessage = await CryptoProcessor.Decrypt(encryptedData, password[..4]);
Пример #7
0
        public async Task TestEmptyMessage()
        {
            var message  = string.Empty;
            var password = "******";

            var encryptedData = await CryptoProcessor.Encrypt(message, password);

            var decryptedMessage = await CryptoProcessor.Decrypt(encryptedData, password);

            Assert.That(decryptedMessage, Is.EqualTo(message));
        }
Пример #8
0
        public async Task TestSimpleEnAndDecryption()
        {
            var message  = "This is a test with umlauts äüö.";
            var password = "******";

            var encryptedData = await CryptoProcessor.Encrypt(message, password);

            Assert.That(encryptedData.Length, Is.AtLeast(message.Length)); // Note: Encrypted data contains salt as well!

            var decryptedMessage = await CryptoProcessor.Decrypt(encryptedData, password);

            Assert.That(decryptedMessage, Is.EqualTo(message));
        }
Пример #9
0
        /// <summary>
        /// Save queries to encoded file
        /// </summary>
        /// <param name="fileName">Xml-file name</param>
        /// <param name="queries">Collection of queries</param>
        /// <param name="cryptoProcessor">Encoder</param>
        public static void SaveToXml(string fileName, List <QueryInfo> queries, CryptoProcessor cryptoProcessor)
        {
            XmlDocument doc = new XmlDocument();

            SaveToXml(fileName, queries);

            doc.PreserveWhitespace = true;

            doc.Load(fileName);

            cryptoProcessor.EncryptXmlDocument(doc);

            doc.Save(fileName);
        }
Пример #10
0
        public async Task TestTooShortPassword4Encryption()
        {
            var message  = "This is a test with umlauts äüö.";
            var password = "******";

            try
            {
                var encryptedData = await CryptoProcessor.Encrypt(message, password);

                Assert.Fail("Should not be reached!");
            }
            catch (CryptographicException e)
            {
                Assert.That(true);
            }
        }
Пример #11
0
        public async Task TestNoMessage()
        {
            string message  = null;
            var    password = "******";

            try
            {
                var encryptedData = await CryptoProcessor.Encrypt(message, password);

                Assert.Fail("Should not be reached!");
            }
            catch (CryptographicException e)
            {
                Assert.That(true);
            }
        }
Пример #12
0
        /// <summary>
        /// Generates a random private key.
        /// </summary>
        /// <param name="password">An optional password to encrypt the key.</param>
        /// <returns>The private key.</returns>
        public static ReadOnlySpan <byte> GeneratePrivateKey(string password = "")
        {
            var privateKey = new Span <byte>(new byte[32]);

            RandomNumberGenerator.Create().GetBytes(privateKey);

            if (!string.IsNullOrWhiteSpace(password))
            {
                using var inputStream  = new MemoryStream(privateKey.ToArray(), false);
                using var outputStream = new MemoryStream();

                CryptoProcessor.Encrypt(inputStream, outputStream, password).Wait();
                privateKey = new Span <byte>(outputStream.ToArray());
            }

            return(privateKey);
        }
Пример #13
0
        /// <summary>
        /// Generates a random private key.
        /// </summary>
        /// <param name="password">An optional password to encrypt the key.</param>
        /// <returns>The private key.</returns>
        public static async Task <byte[]> GeneratePrivateKeyAsync(string password = "")
        {
            var privateKey = new byte[32];
            await Task.Run(() => RandomNumberGenerator.Create().GetBytes(privateKey));

            if (!string.IsNullOrWhiteSpace(password))
            {
                await using var inputStream  = new MemoryStream(privateKey, false);
                await using var outputStream = new MemoryStream();

                await CryptoProcessor.Encrypt(inputStream, outputStream, password);

                privateKey = outputStream.ToArray();
            }

            return(privateKey);
        }
Пример #14
0
        /// <summary>
        /// Load queries from Xml-file
        /// </summary>
        /// <param name="fileName">Xml-file name</param>
        /// <param name="cryptoProcessor">Encoder</param>
        /// <param name="isExternal">Is opened from user file template</param>
        /// <returns>List of queries</returns>
        public static List <QueryInfo> LoadFromXml(string fileName, CryptoProcessor cryptoProcessor, bool isExternal)
        {
            if (AppVersionHelper.IsDebug() || isExternal)
            {
                if (cryptoProcessor == null)
                {
                    return(LoadFromXml(fileName));
                }
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(fileName);

                if (AppVersionHelper.IsRelease() || (AppVersionHelper.IsNotRelease() && cryptoProcessor != null))
                {
                    cryptoProcessor.DecryptXmlDocument(doc);
                }

                byte[] bytes = Encoding.UTF8.GetBytes(doc.OuterXml);

                XmlSerializer s = new XmlSerializer(typeof(LoaderRootWrapper));

                using (var includingReader = new MemoryStream(bytes))
                {
                    using (var xmlReader = XmlReader.Create(includingReader, XmlUtils.GetXmlReaderSettings()))
                    {
                        return(GetQueries(((LoaderRootWrapper)s.Deserialize(xmlReader))));
                    }
                }
            }
            catch (Exception exception)
            {
                log.Error(exception);

                if (AppVersionHelper.IsDebug() || isExternal)
                {
                    return(LoadFromXml(fileName));
                }

                throw;
            }
        }
 public static void SetDatabaseMasterPassword(string encryptedTextPassword = "")
 {
     if (!string.IsNullOrWhiteSpace(encryptedTextPassword))
     {
         string unencryptedPassword = CryptoProcessor.Decrypt(encryptedTextPassword);
         if (string.IsNullOrWhiteSpace(unencryptedPassword))
         {
             throw new ArgumentException("Encrypted Text Failed to decrypt. Please Reset the Password and update storage");
         }
         SecureString secureStringPassword = new SecureString();
         foreach (char c in unencryptedPassword)
         {
             secureStringPassword.AppendChar(c);
         }
         DatabaseInfo.DatabaseMasterPassword = secureStringPassword;
         DatabaseInfo.DatabaseMasterPassword.MakeReadOnly();
     }
 }
Пример #16
0
        public static Template GetTemplateByFile(string strFileName)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(strFileName);

                Template retTemplate;

                if (AppVersionHelper.IsNotDebug())
                {
                    var cryptoProcessor = new CryptoProcessor(
                        Program.Model.Settings.SystemSettings.PublicKeyXmlSign,
                        Program.Model.Settings.SystemSettings.PrivateKeyXmlDecrypt);

                    cryptoProcessor.DecryptXmlDocument(doc);
                }

                using (var nodeReader = new XmlNodeReader(doc))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Template));

                    using (var xmlReader = XmlReader.Create(nodeReader, XmlUtils.GetXmlReaderSettings()))
                    {
                        retTemplate = (Template)serializer.Deserialize(xmlReader);
                    }
                }

                return(retTemplate);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return(null);
        }
        public VisualizeData GetVisualizeData(
            NodeDataProvider dataProvider,
            GraphicsInfo graphicsInfo
            )
        {
            XmlDocument          xmlData       = dataProvider.XmlDocument;
            MultyQueryResultInfo queriesResult = dataProvider.QueryResult;

            VisualizeData result = new VisualizeData
            {
                NodeLastUpdated        = queriesResult.NodeLastUpdated,
                NodeLastUpdateDuration = queriesResult.NodeLastUpdateDuration
            };

            if (xmlData != null && xmlData.DocumentElement != null)
            {
                result.SourceXml = xmlData.FormatXml();
            }

            ConcreteTemplateNodeDefinition nodeDefinition = dataProvider.NodeDefinition;

            string xslFileName = GetXslFileName(nodeDefinition);

            if (xslFileName != null && File.Exists(xslFileName))
            {
                XmlDocument xslDoc = new XmlDocument();

                xslDoc.Load(xslFileName);

                ConnectionGroupInfo connectionGroup = nodeDefinition.Connection;

                if (AppVersionHelper.IsNotDebug() && !connectionGroup.IsExternal)
                {
                    CryptoProcessor cryptoProcessor = new CryptoProcessor(
                        this._model.Settings.SystemSettings.PublicKeyXmlSign,
                        this._model.Settings.SystemSettings.PrivateKeyXmlDecrypt
                        );

                    cryptoProcessor.DecryptXmlDocument(xslDoc);
                }

                try
                {
                    XslPreprocessManager preprocessManager = GetManager(
                        dataProvider,
                        graphicsInfo
                        );

                    List <PreprocessorAreaData> datas;

                    using (preprocessManager.ExecuteXslPreprocessing(xslDoc, out datas))
                    {
                    }

                    foreach (PreprocessorAreaData preprocessorAreaData in datas)
                    {
                        preprocessorAreaData.CheckPreprocessors();
                    }

                    result.PreprocessorAreas = datas.ToList();
                }
                catch (Exception ex)
                {
                    log.ErrorFormat(
                        "nodeDefinition.TemplateNode.Queries(.Name)='{0}';xslFileName='{1}';Exception:'{2}'",
                        nodeDefinition.TemplateNode.Queries.Select(q => q.QueryName).Join(", "),
                        xslFileName,
                        ex
                        );
                }
            }

            return(result);
        }
Пример #18
0
        /// <summary>
        /// Load queries with signature check
        /// </summary>
        /// <param name="filename">Xml-file name</param>
        /// <param name="isExternal">Is opened from user file template</param>
        /// <returns>Queries list</returns>
        public List <QueryInfo> LoadQueries(string filename, bool isExternal)
        {
            log.InfoFormat("filename:'{0}',isExternal:'{1}'",
                           filename ?? "<null>",
                           isExternal
                           );

            List <string>   wrongQueries    = new List <string>();
            CryptoProcessor cryptoProcessor = null;

            try
            {
                if (AppVersionHelper.IsNotDebug())
                {
                    cryptoProcessor = new CryptoProcessor(
                        Settings.SystemSettings.PublicKeyXmlSign,
                        Settings.SystemSettings.PrivateKeyXmlDecrypt
                        );
                }
            }
            catch (System.Security.XmlSyntaxException ex)
            {
                log.Error(ex);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                log.Error(ex.GetBaseException());
            }

            List <QueryInfo> queries = QueriesLoader.LoadFromXml(filename, cryptoProcessor, isExternal);

            for (int i = queries.Count - 1; i >= 0; i--)
            {
                QueryInfo query = queries[i];

                log.InfoFormat("query:'{0}'", query);

                if (AppVersionHelper.IsNotDebug() && !isExternal)
                {
                    for (int j = query.DatabaseSelect.Count - 1; j >= 0; j--)
                    {
                        QueryItemInfo queryItem = query.DatabaseSelect[j];

                        if (cryptoProcessor != null && !cryptoProcessor.Verify(queryItem.Text, queryItem.Signature))
                        {
                            if (!wrongQueries.Contains(query.Name))
                            {
                                wrongQueries.Add(query.Name);
                            }

                            query.DatabaseSelect.RemoveAt(j);
                        }
                    }

                    for (int j = query.Items.Count - 1; j >= 0; j--)
                    {
                        QueryItemInfo queryItem = query.Items[j];

                        log.InfoFormat("queryItem.Text:'{0}'", queryItem.Text);

                        if (cryptoProcessor != null && !cryptoProcessor.Verify(queryItem.Text, queryItem.Signature))
                        {
                            if (!wrongQueries.Contains(query.Name))
                            {
                                wrongQueries.Add(query.Name);
                            }

                            query.Items.RemoveAt(j);
                        }
                    }
                }

                if (query.Items.Count == 0)
                {
                    queries.RemoveAt(i);
                }
            }

            if ((Settings.WarnAboutUnsignedQuery) && (wrongQueries.Count > 0))
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(filename + Environment.NewLine + Environment.NewLine);

                foreach (string wrongQuery in wrongQueries)
                {
                    sb.Append(wrongQuery + Environment.NewLine);
                }

                MessageBox.Show(sb.ToString(), LocaleManager.GetLocalizedText(LocaleManager.Exceptions, "wrongQueriesSignatures"));
            }

            return(queries);
        }
Пример #19
0
        /// <summary>
        /// The validate license.
        /// </summary>
        /// <param name="fullSlowCheck">The full slow check.</param>
        /// <returns>
        /// The <see cref="LicenseState" />.
        /// </returns>
        public LicenseState ValidateLicense(bool fullSlowCheck, bool withCheckConnection = true)
        {
            if (this._foundLicenseState != null)
            {
                return(this._foundLicenseState);
            }

            this._foundLicenseState = new LicenseState
            {
                Instance = this.Instance
            };

            if (this.LicenseInfo == null)
            {
                if (AppVersionHelper.IsNotRelease())
                {
                    return(this._foundLicenseState);
                }

                this._foundLicenseState.AddProblem(LicenseProblemType.LicenseNotDefined, string.Empty);
            }
            else
            {
                this._foundLicenseState.AddProblems(this.LicenseInfo.IsLicenseInfoCorrect());

                DateTime dateTime;

                if (fullSlowCheck && withCheckConnection)
                {
                    if (this._serverProperties != null)
                    {
                        dateTime = this._serverProperties.Date;
                    }
                    else
                    {
                        try
                        {
                            ServerProperties props = ServerProperties.Query(this);

                            dateTime = props.Date;

                            this._serverProperties = props;
                        }
                        catch (Exception exc)
                        {
                            log.Error("Exception:", exc);

                            log.ErrorFormat(
                                "Instance:'{0}';Authentication:'{1}';Exception:'{2}'",
                                Instance,
                                Authentication,
                                exc
                                );

                            dateTime = DateTime.MaxValue;
                        }
                    }
                }
                else
                {
                    dateTime = DateTime.Now;
                }

                var buildDateObject =
                    Assembly.GetExecutingAssembly()
                    .GetCustomAttributes(typeof(BuildDateAttribute), false)
                    .FirstOrDefault();

                DateTime buildDate = DateTime.MaxValue;

                if (buildDateObject is BuildDateAttribute)
                {
                    buildDate = (buildDateObject as BuildDateAttribute).BuildDate;
                }

                if (dateTime == DateTime.MaxValue)
                {
                    this._foundLicenseState.AddProblem(LicenseProblemType.CantConnect, string.Empty);
                }
                else if (this._foundLicenseState.IsCorrect && fullSlowCheck && (dateTime > this.LicenseInfo.ExpiryDate))
                {
                    this._foundLicenseState.AddProblem(LicenseProblemType.Expired, string.Empty);
                }
                else if (buildDate > this.LicenseInfo.BuildExpiryDate)
                {
                    this._foundLicenseState.AddProblem(LicenseProblemType.BuildExpiryDateNotValid, string.Empty);
                }
                else
                {
                    if (AppVersionHelper.IsNotDebug())
                    {
                        string hash = this.GetHash();

                        CryptoProcessor cryptoProcessor =
                            new CryptoProcessor(
                                Program.Model.Settings.SystemSettings.PublicKeyXmlSign,
                                Program.Model.Settings.SystemSettings.PrivateKeyXmlDecrypt
                                );

                        if (!cryptoProcessor.Verify(hash, this.LicenseInfo.Signature))
                        {
                            this._foundLicenseState.AddProblem(LicenseProblemType.WrongSignature, string.Empty);
                        }
                    }
                }
            }

            var result = this._foundLicenseState;

            if (!fullSlowCheck)
            {
                this._foundLicenseState = null;
            }

            return(result);
        }
Пример #20
0
        /// <summary>
        /// Item1 = name. Item2 = directory.
        /// </summary>
        /// <param name="templateID"></param>
        /// <returns></returns>
        public static Tuple <string, string> GetTemplateById(string templateID)
        {
            string          strFileName   = string.Empty;
            string          strFolderName = string.Empty;
            List <Template> retList       = new List <Template>();
            DirectoryInfo   directoryInfo = new DirectoryInfo(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Program.Model.Settings.TemplateDirectory));

            if (directoryInfo.Exists)
            {
                try
                {
                    var serializer = new XmlSerializer(typeof(Template));

                    var files = directoryInfo.GetFiles("*.xml");

                    foreach (FileInfo file in files)
                    {
                        try
                        {
                            var doc = new XmlDocument();
                            doc.Load(file.FullName);

                            if (AppVersionHelper.IsNotDebug())
                            {
                                var cryptoProcessor = new CryptoProcessor(
                                    Program.Model.Settings.SystemSettings.PublicKeyXmlSign,
                                    Program.Model.Settings.SystemSettings.PrivateKeyXmlDecrypt);

                                cryptoProcessor.DecryptXmlDocument(doc);
                            }

                            //
                            // #248 - fix memory leaks during XML files processing
                            //
                            // var nodeReader = new XmlNodeReader(doc);
                            using (var nodeReader = new XmlNodeReader(doc))
                            {
                                using (var xmlReader = XmlReader.Create(nodeReader, XmlUtils.GetXmlReaderSettings()))
                                {
                                    var template = (Template)serializer.Deserialize(xmlReader);

                                    if (templateID == template.Id)
                                    {
                                        strFileName   = file.Name;
                                        strFolderName = file.DirectoryName;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex);

                            if (file != null)
                            {
                                log.ErrorFormat("File:'{0}'", file);
                            }

                            log.ErrorFormat("Folder:'{0}'", directoryInfo);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    log.ErrorFormat("Folder:'{0}'", directoryInfo);
                }
            }
            else
            {
                log.Error("Folder with models is not exists");
                log.ErrorFormat("Folder:'{0}'", directoryInfo);
            }

            return(new Tuple <string, string>(strFileName, strFolderName));
        }