Beispiel #1
0
        public static void CreateInfoFile(string strPlgxPath)
        {
            FileStream fsOut = null;
            TextWriter twLog = null;

            try
            {
                fsOut = new FileStream(strPlgxPath + ".txt", FileMode.Create,
                                       FileAccess.Write, FileShare.None);
                twLog = new StreamWriter(fsOut, new UTF8Encoding(false));

                NullStatusLogger sl = new NullStatusLogger();
                LoadPriv(strPlgxPath, sl, false, false, false, twLog);
            }
            catch (Exception ex)
            {
                MessageService.ShowWarning(strPlgxPath, ex);
            }
            finally
            {
                if (twLog != null)
                {
                    twLog.Close();
                }
                if (fsOut != null)
                {
                    fsOut.Close();
                }
            }
        }
        public void Save()
        {
            IStatusLogger logger = new NullStatusLogger();

            this.PwDatabase.Save(logger);
            logger.EndLogging();
        }
        private static void OpenDatabase()
        {
            if (!string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseFileName))
            {
                if (!string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseFileFullLocation))
                {
                    if (!File.Exists(DatabaseInfo.DatabaseFileFullLocation))
                    {
                        throw new FileNotFoundException($"DATABASE FILE ERROR{DatabaseInfo.DatabaseFileFullLocation} does not exists. Please check the locations and try again.");
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseKeyFileName))
            {
                if (!string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseKeyFileFullLocation))
                {
                    if (!File.Exists(DatabaseInfo.DatabaseKeyFileFullLocation))
                    {
                        throw new FileNotFoundException($"KEY FILE ERROR: {DatabaseInfo.DatabaseKeyFileFullLocation} does not exists. Please check the locations and try again.");
                    }
                }
            }

            try
            {
                var ioConnInfo = new IOConnectionInfo()
                {
                    Path = DatabaseInfo.DatabaseFileFullLocation
                };

                var compKey = CreateCompositeKey();
#if DEBUG
                IStatusLogger statusLogger = new DebugStatusLogger();
                Database.Open(ioConnInfo, compKey, statusLogger);
#else
                //This is a do nothing logger but the Interface should be implemented if you are going to make your application public, I recommend creating an applications insights account and using the logger to write trace events to that service.
                IStatusLogger nullStatusLogger = new NullStatusLogger();
                Database.Open(ioConnInfo, compKey, nullStatusLogger);
#endif

                IsDatabaseOpen = true;
            }
            catch (Exception e)
            {
                throw;
            }
        }
Beispiel #4
0
        public static bool Export(PwExportInfo pwExportInfo, string strFormatName,
                                  IOConnectionInfo iocOutput)
        {
            if (strFormatName == null)
            {
                throw new ArgumentNullException("strFormatName");
            }
            // iocOutput may be null

            FileFormatProvider prov = Program.FileFormatPool.Find(strFormatName);

            if (prov == null)
            {
                return(false);
            }

            NullStatusLogger slLogger = new NullStatusLogger();

            return(Export(pwExportInfo, prov, iocOutput, slLogger));
        }
Beispiel #5
0
        private static List <FsxContext> Find(FsxMatchFn fMatch, IStatusLogger sl,
                                              string strRootPath)
        {
            if (sl == null)
            {
                Debug.Assert(false); sl = new NullStatusLogger();
            }

            List <FsxContext> lContexts = new List <FsxContext>();

            if (!string.IsNullOrEmpty(strRootPath))
            {
                lContexts.Add(new FsxContext(strRootPath, string.Empty, fMatch));
            }
            else
            {
                DriveInfo[] vDrives = DriveInfo.GetDrives();
                if (vDrives == null)
                {
                    Debug.Assert(false); vDrives = new DriveInfo[0];
                }
                foreach (DriveInfo di in vDrives)
                {
                    if (di == null)
                    {
                        Debug.Assert(false); continue;
                    }

                    try
                    {
                        if (!di.IsReady)
                        {
                            continue;
                        }

                        string strRoot = di.RootDirectory.FullName;
                        if (string.IsNullOrEmpty(strRoot))
                        {
                            Debug.Assert(false); continue;
                        }

                        string strVolumeLabel = string.Empty;
                        try { strVolumeLabel = (di.VolumeLabel ?? string.Empty); }
                        catch (Exception) { Debug.Assert(false); }

                        lContexts.Add(new FsxContext(strRoot, strVolumeLabel, fMatch));
                    }
                    catch (Exception) { Debug.Assert(false); }
                }
            }

            for (int i = lContexts.Count - 1; i >= 0; --i)
            {
                FsxContext ctx = lContexts[i];

                try
                {
                    Thread th = new Thread(delegate()
                    {
                        try
                        {
                            try { FindInDirectory(ctx.RootDirectory, ctx); }
                            catch (Exception) { Debug.Assert(false); }

                            ctx.End = true;
                        }
                        catch (Exception) { Debug.Assert(false); }
                    });
                    th.Start();
                }
                catch (Exception) { Debug.Assert(false); lContexts.RemoveAt(i); }
            }

            lContexts.Sort(FsxContext.CompareByRoot);
            sl.SetText(GetSearchingText(lContexts), LogStatusType.Info);

            List <FsxContext> lRunning = new List <FsxContext>(lContexts);
            int msSleep = Math.Max(PwDefs.UIUpdateDelay / 4, 1);

            while (lRunning.Count != 0)
            {
                try
                {
                    Thread.Sleep(msSleep);

                    for (int i = lRunning.Count - 1; i >= 0; --i)
                    {
                        if (lRunning[i].End)
                        {
                            lRunning.RemoveAt(i);
                            sl.SetText(GetSearchingText(lRunning), LogStatusType.Info);
                        }
                    }

                    if (!sl.ContinueWork())
                    {
                        foreach (FsxContext ctx in lRunning)
                        {
                            ctx.End = true;
                        }
                        lRunning.Clear();
                    }
                }
                catch (Exception) { Debug.Assert(false); }
            }

            return(lContexts);
        }
Beispiel #6
0
        /*
         * TODO: Regenerate Salt for Keys
         * Open C# Interactive from the View menu | View -> Other Windows -> C# interactive : in most cases it will pop up next to the Output window.
         * Copy paste the line below to generate a new text based Guid. (Guid as Text) Copy paste and replace the keys above generate 4 new Salt Keys.
         * Guid.NewGuid().ToJSON();
         * Example : "13d7e13e-a63c-42ce-beff-e5d6346d949d", "cb3562e3-0d49-47c4-b9e2-49506259afe6", "c198bcd6-af01-46ba-a902-57973b621899","20831b9b-93be-433f-92d4-aa87cb997ba1"
         */
        //public static List<string> ServiceKeysForSaltLookup = new List<string> { "13d7e13e-a63c-42ce-beff-e5d6346d949d", "cb3562e3-0d49-47c4-b9e2-49506259afe6", "c198bcd6-af01-46ba-a902-57973b621899", "20831b9b-93be-433f-92d4-aa87cb997ba1" };


        public static string GetConfigurationValue(string key)
        {
            //String strAppPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            //String strFilePath = Path.Combine(strAppPath, "Resources");
            //String strFullFilename = Path.Combine(strFilePath, "MyFaceRecongnitionApplicationDB.kdbx");

            //string dbpath = @"W:\MyFaceRecongnitionApplicationDB.kdbx";
            //string keypath = $@"W:\MyFaceRecongnitionApplicationDB.key";

            var ioConnInfo = new IOConnectionInfo {
                Path = ""
            };

            var compKey = new CompositeKey();

            compKey.AddUserKey(new KcpKeyFile(new MemoryStream(Facial_Recognition_Library.Properties.Resources.MyFaceRecongnitionApplicationDBKey), "MyFaceRecongnitionApplicationDB"));
            //compKey.AddUserKey(new KcpPassword(masterpw));
            //This is a do nothing logger but the Interface should be implimented if you are going to make your application public, I recommend creating an applications insights account and using the logger to write trace events to that service.
            IStatusLogger d = new NullStatusLogger();

            KeePassLib.PwDatabase db = new PwDatabase();

            ioConnInfo.StreamFileName = "MyFaceRecongnitionApplicationDB";
            ioConnInfo.Stream         = new MemoryStream(Facial_Recognition_Library.Properties.Resources.MyFaceRecongnitionApplicationDB);

            db.Open(ioConnInfo, compKey, d);

            /*
             * This could cause a problem. if I move the Service Type into another Assembly this would be incorrect or bomb if no additional app.config settings file was available.
             *  in other words if the config file doesn't contain the appropreate keys, this will throw an error, you could add additional reference checks to see if any other
             *  referenced dlls contain a config file in the directory.
             *  Another method is to have certian types of key's stored in certain locations, Passwords and such in asecure location and other settings (user|Application)
             *  stored in the Registry or user path.
             *  This sets you up to do just that.
             *  Check out the http://keepass.info source, and consider including it in your applicaitons to store password or encoded information.
             */

            //First: Retrieve the Encryption Salt
            //Second: Get Private Key
            string PrivateKey = GetValueFromDB(ref db, "PrivateSharedSecret");
            string Salt       = GetValueFromDB(ref db, "ServicePasswordSalt");

            if (string.IsNullOrWhiteSpace(PrivateKey))
            {
                throw new Exception("Private Key value was not found.");
            }
            if (string.IsNullOrWhiteSpace(Salt))
            {
                throw new Exception("Salt value was not found.");
            }

            Assembly service = Assembly.GetAssembly(typeof(Facial_Recognition_Library.ServiceDetails));
            //Here is where you can adjust the configruation file that is opened as apart of Configuration retrieval.
            //Configuration config = ConfigurationManager.OpenExeConfiguration(service.Location);

            var myCrypto = new Facial_Recognition_Library.Crypto();

            if (!string.IsNullOrWhiteSpace(config.AppSettings[key]))
            {
                string ConfigValue             = config.AppSettings[key];
                string ConfigsThatAreEncrypted = config.AppSettings["EncryptedArray"];
                if (ConfigsThatAreEncrypted.Contains(key))
                {
                    ConfigValue = myCrypto.DecryptStringAES(ConfigValue, PrivateKey, Salt);
                }
                return(ConfigValue);
            }
            else
            {
                //Use K to process the Encrypted Key
                string KeyValue = config.AppSettings[key];
                if (string.IsNullOrWhiteSpace(KeyValue))
                {
                    string value = GetValueFromDB(ref db, key);
                    return(value);
                }
                else
                {
                    string value = Facial_Recognition_Library.Crypto.EncryptStringAES(KeyValue, PrivateKey, Salt);
                    return(value);
                }
            }
        }
Beispiel #7
0
        private static IDictionary <string, ProtectedString> OpenKeePassDB(SecureString Password)
        {
            PwDatabase       PwDB    = new PwDatabase();
            IOConnectionInfo mioInfo = new IOConnectionInfo
            {
                Path = pathToKeePassDb
            };
            CompositeKey compositeKey = new CompositeKey();

            compositeKey.AddUserKey(new KcpPassword(Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(Password))));
            IStatusLogger statusLogger = new NullStatusLogger();

            Dictionary <string, ProtectedString> dict = new Dictionary <string, ProtectedString>();

            try
            {
                PwDB.Open(mioInfo, compositeKey, statusLogger);
                PwObjectList <PwGroup> groups = PwDB.RootGroup.GetGroups(true);

                if (workingMode == WorkingModes.Prepare)
                {
                    // Check whether the requested group already exists
                    if (!groups.Any(x => x.Name.Equals(groupName)))
                    {
                        PwDB.RootGroup.AddGroup(new PwGroup()
                        {
                            Name = groupName
                        }, true);
                        Trace.TraceInformation($"The Group {groupName} has been added to KeePass DB");
                    }
                    PwGroup grp = PwDB.RootGroup.GetGroups(true).Where(x => x.Name.Equals(groupName)).First();
                    // Check if the required entry doesn't exist in the group
                    if (!grp.GetEntries(false).Any(x => x.Strings.ReadSafe("Title").Equals(entryName)))
                    {
                        //Need to have a local variable for Protected dic
                        //otherwise the clause becomes too complecated for reading
                        ProtectedStringDictionary d = new ProtectedStringDictionary();
                        d.Set("Title", new ProtectedString(true, entryName));
#pragma warning disable CS0618 // Type or member is obsolete
                        //They tell it is obsolete and recommend to use any other constructor,
                        //but, actually, there's no other to be used.
                        grp.AddEntry(new PwEntry(grp, true, true)
                        {
                            Strings = d
                        }, true);
#pragma warning restore CS0618 // Type or member is obsolete
                        Trace.TraceInformation($"The Entry {entryName} has been added to KeePass DB");
                    }
                    PwEntry ent = grp.GetEntries(false).Where(x => x.Strings.ReadSafe("Title").Equals(entryName)).First();
                    //Create a value for password
                    ProtectedString aesPwd = new ProtectedString();
                    PwGenerator.Generate(out aesPwd, new PwProfile()
                    {
                        Length  = 16,
                        CharSet = new PwCharSet(PwCharSet.LowerCase +
                                                PwCharSet.UpperCase +
                                                PwCharSet.Digits +
                                                PwCharSet.PrintableAsciiSpecial)
                    },
                                         UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(16)),
                                         new CustomPwGeneratorPool());
                    //Create a vlaue for Salt
                    ProtectedString salt = new ProtectedString();
                    PwGenerator.Generate(out salt, new PwProfile()
                    {
                        Length  = 26,
                        CharSet = new PwCharSet(PwCharSet.LowerCase +
                                                PwCharSet.UpperCase +
                                                PwCharSet.Digits +
                                                PwCharSet.PrintableAsciiSpecial)
                    },
                                         UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(28)),
                                         new CustomPwGeneratorPool());
                    ent.Strings.Set("AESpassword", new ProtectedString(true, aesPwd.ReadString()));
                    Trace.TraceInformation($"The value of the AESPass in the Entry {entryName} has been added to KeePass DB");
                    ent.Strings.Set("Salt", new ProtectedString(true, salt.ReadString()));
                    Trace.TraceInformation($"The value of the Salt in the Entry {entryName} has been added to KeePass DB");
                    // Create IV
                    SymmetricAlgorithm cipher = SymmetricAlgorithm.Create("AesManaged");
                    cipher.Mode    = CipherMode.CBC;
                    cipher.Padding = PaddingMode.PKCS7;
                    ent.Strings.Set("IV", new ProtectedString(true, Convert.ToBase64String(cipher.IV)));
                    Trace.TraceInformation($"The value of the IV in the Entry {entryName} has been added to KeePass DB");
                    PwDB.Save(statusLogger);
                    // Add dummy values to the dictionary to pass the check in the end of the method
                    dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt")));
                    dict.Add("Password", new ProtectedString(true, "dummy"));
                    dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword")));
                    dict.Add("UserName", new ProtectedString(true, "dummy"));
                    dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV")));
                    dict.Add("SecurityToken", new ProtectedString(true, "dummy"));
                }
                else
                {
                    foreach (PwGroup grp in groups)
                    {
                        if (grp.Name.Equals(groupName))
                        {
                            PwObjectList <PwEntry> entries = grp.GetEntries(false);
                            foreach (PwEntry ent in entries)
                            {
                                if (ent.Strings.ReadSafe("Title").Equals(entryName))
                                {
                                    dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt")));
                                    dict.Add("Password", new ProtectedString(true, ent.Strings.ReadSafe("Password")));
                                    dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword")));
                                    dict.Add("UserName", new ProtectedString(true, ent.Strings.ReadSafe("UserName")));
                                    dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV")));
                                    dict.Add("SecurityToken", new ProtectedString(true, ent.Strings.ReadSafe("SecurityToken")));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError($"Failed to open KeePassDb \n{ex.Message}");
            }
            finally
            {
                PwDB.Close();
            }
            //Delete key-value pairs where values are empty
            dict.Where(d => d.Value.IsEmpty).ToList().ForEach(t => dict.Remove(t.Key));
            return(dict);
        }