Example #1
0
        /// <summary>
        /// Common program initialization function that can also be
        /// used by applications that use KeePass as a library
        /// (like e.g. KPScript).
        /// </summary>
        public static bool CommonInit()
        {
            m_bDesignMode = false;             // Again, for the ones not calling Main

            m_rndGlobal = CryptoRandom.NewWeakRandom();

            InitEnvSecurity();
            MonoWorkarounds.Initialize();

            // try { NativeMethods.SetProcessDPIAware(); }
            // catch(Exception) { }

            // Do not run as AppX, because of compatibility problems
            // (unless we're a special compatibility build)
            if (WinUtil.IsAppX && !IsBuildType(
                    "CDE75CF0D4CA04D577A5A2E6BF5D19BFD5DDBBCF89D340FBBB0E4592C04496F1"))
            {
                return(false);
            }

            try { SelfTest.TestFipsComplianceProblems(); }
            catch (Exception exFips)
            {
                MessageService.ShowWarning(KPRes.SelfTestFailed, exFips);
                return(false);
            }

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            KdbxFile.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();

            if (m_appConfig.Security.ProtectProcessWithDacl)
            {
                KeePassLib.Native.NativeMethods.ProtectProcessWithDacl();
            }

            m_appConfig.Apply(AceApplyFlags.All);

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            // InitEnvWorkarounds();
            LoadTranslation();

            CustomResourceManager.Override(typeof(KeePass.Properties.Resources));

            return(true);
        }
Example #2
0
        private void OnCheckedChangedAutoRun(object sender, EventArgs e)
        {
            if (m_bLoadingSettings)
            {
                return;
            }

            bool bRequested = m_cbAutoRun.Checked;
            bool bCurrent   = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);

            if (bRequested != bCurrent)
            {
                string strPath = WinUtil.GetExecutable().Trim();
                if (strPath.StartsWith("\"") == false)
                {
                    strPath = "\"" + strPath + "\"";
                }
                ShellUtil.SetStartWithWindows(AppDefs.AutoRunName, strPath,
                                              bRequested);

                bool bNew = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);

                if (bNew != bRequested)
                {
                    m_cbAutoRun.Checked = bNew;
                }
            }
        }
Example #3
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            string strVersion = PwDefs.VersionString;

            if (Program.IsDevelopmentSnapshot())
            {
                strVersion += " - Dev.";
                try
                {
                    string   strExe = WinUtil.GetExecutable();
                    FileInfo fi     = new FileInfo(strExe);
                    strVersion += " " + fi.LastWriteTimeUtc.ToString("yyMMdd");
                }
                catch (Exception) { Debug.Assert(false); }
            }

            const string strParamPlh = @"{PARAM}";
            string       strBits     = KPRes.BitsA;

            if (strBits.IndexOf(strParamPlh) >= 0)
            {
                strVersion += (" (" + strBits.Replace(strParamPlh,
                                                      (IntPtr.Size * 8).ToString()) + ")");
            }
            else
            {
                Debug.Assert(false);
            }

            string strTitle = PwDefs.ProductName;
            string strDesc  = KPRes.Version + " " + strVersion;

            Icon icoSc = AppIcons.Get(AppIconType.Main, new Size(
                                          DpiUtil.ScaleIntX(48), DpiUtil.ScaleIntY(48)), Color.Empty);

            BannerFactory.CreateBannerEx(this, m_bannerImage, icoSc.ToBitmap(),
                                         strTitle, strDesc);
            this.Icon = AppIcons.Default;

            Debug.Assert(!m_lblCopyright.AutoSize);             // For RTL support
            m_lblCopyright.Text = PwDefs.Copyright + ".";

            string strCompValueHdr = KPRes.Version + "/" + KPRes.Status;

            if (Regex.IsMatch(strCompValueHdr, "\\s"))
            {
                strCompValueHdr = KPRes.Version + " / " + KPRes.Status;
            }

            m_lvComponents.Columns.Add(KPRes.Component, 100);
            m_lvComponents.Columns.Add(strCompValueHdr, 100);

            try { GetAppComponents(strVersion); }
            catch (Exception) { Debug.Assert(false); }

            UIUtil.SetExplorerTheme(m_lvComponents, false);
            UIUtil.ResizeColumns(m_lvComponents, true);
        }
Example #4
0
        public string GetKeySource(IOConnectionInfo ioDatabase, bool bGetKeyFile)
        {
            if (ioDatabase == null)
            {
                throw new ArgumentNullException("ioDatabase");
            }

            string strDb = ioDatabase.Path;

            if ((strDb.Length > 0) && ioDatabase.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
            {
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);
            }

            foreach (AceKeyAssoc kfp in m_vKeySources)
            {
                if (strDb.Equals(kfp.DatabasePath, StrUtil.CaseIgnoreCmp))
                {
                    return(bGetKeyFile ? kfp.KeyFilePath : kfp.KeyProvider);
                }
            }

            return(null);
        }
Example #5
0
        private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
        {
            if (ioc == null)
            {
                Debug.Assert(false); return;
            }

            if (!ioc.IsLocalFile())
            {
                return;
            }

            // Update path separators for current system
            ioc.Path = UrlUtil.ConvertSeparators(ioc.Path);

            string strBase = WinUtil.GetExecutable();
            bool   bIsAbs  = UrlUtil.IsAbsolutePath(ioc.Path);

            if (bMakeAbsolute && !bIsAbs)
            {
                ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
            }
            else if (!bMakeAbsolute && bIsAbs)
            {
                ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
            }
        }
Example #6
0
 private void OnBtnFileExtCreate(object sender, EventArgs e)
 {
     // ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
     //	KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, true);
     WinUtil.RunElevated(WinUtil.GetExecutable(), "-" +
                         AppDefs.CommandLineOptions.FileExtRegister, false);
 }
Example #7
0
        internal static string GetLanguagesDir(AceDir d, bool bTermSep)
        {
            string str;

            if (d == AceDir.App)
            {
                str = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                               true, false) + AppDefs.LanguagesDir;
            }
            else if (d == AceDir.User)
            {
                str = UrlUtil.EnsureTerminatingSeparator(
                    AppConfigSerializer.AppDataDirectory, false) +
                      AppDefs.LanguagesDir;
            }
            else
            {
                Debug.Assert(false); return(string.Empty);
            }

            if (bTermSep)
            {
                str = UrlUtil.EnsureTerminatingSeparator(str, false);
            }

            return(str);
        }
Example #8
0
 private void OnBtnFileExtRemove(object sender, EventArgs e)
 {
     // ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt,
     //	AppDefs.FileExtension.ExtId);
     WinUtil.RunElevated(WinUtil.GetExecutable(), "-" +
                         AppDefs.CommandLineOptions.FileExtUnregister, false);
 }
Example #9
0
        private static bool IsBuildType(string str)
        {
            try
            {
                string strFile = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                          true, false) + "Application.ini";
                if (!File.Exists(strFile))
                {
                    return(false);
                }

                IniFile f       = IniFile.Read(strFile, StrUtil.Utf8);
                string  strType = f.Get("Application", "Type");
                if (string.IsNullOrEmpty(strType))
                {
                    return(false);
                }

                byte[] pb = CryptoUtil.HashSha256(StrUtil.Utf8.GetBytes(strType.Trim()));
                return(string.Equals(MemUtil.ByteArrayToHexString(pb),
                                     str, StrUtil.CaseIgnoreCmp));
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Example #10
0
        private void GetAppComponents()
        {
            ListViewItem lvi = new ListViewItem(KPRes.KeePassLibCLong);

            if (!Kdb3File.IsLibraryInstalled())
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(Kdb3Manager.KeePassVersionString + " (0x" +
                                 Kdb3Manager.LibraryBuild.ToString("X4") + ")");
            }
            m_lvComponents.Items.Add(lvi);

            lvi = new ListViewItem(KPRes.XslStylesheets);
            string strPath = WinUtil.GetExecutable();

            strPath = UrlUtil.GetFileDirectory(strPath, true);
            bool bInstalled = File.Exists(strPath + AppDefs.XslFileHtmlLite);

            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlFull);
            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlTabular);

            if (!bInstalled)
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(PwDefs.VersionString);
            }
            m_lvComponents.Items.Add(lvi);
        }
Example #11
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Keyboard_Layout,
                                         KPRes.SelectLanguage, KPRes.SelectLanguageDesc);
            this.Icon = Properties.Resources.KeePass;
            this.Text = KPRes.SelectLanguage;

            int nWidth = m_lvLanguages.ClientRectangle.Width / 4;

            m_lvLanguages.Columns.Add(KPRes.AvailableLanguages, nWidth);
            m_lvLanguages.Columns.Add(KPRes.Version, nWidth);
            m_lvLanguages.Columns.Add(KPRes.Author, nWidth);
            m_lvLanguages.Columns.Add(KPRes.Contact, nWidth);

            ListViewItem lvi = m_lvLanguages.Items.Add("English", 0);

            lvi.SubItems.Add(PwDefs.VersionString);
            lvi.SubItems.Add(AppDefs.DefaultTrlAuthor);
            lvi.SubItems.Add(AppDefs.DefaultTrlContact);

            List <string> vList = new List <string>();

            GetAvailableTranslations(AppConfigSerializer.AppDataDirectory, vList);
            GetAvailableTranslations(AppConfigSerializer.LocalAppDataDirectory, vList);

            string strExe  = WinUtil.GetExecutable();
            string strPath = UrlUtil.GetFileDirectory(strExe, false, true);

            GetAvailableTranslations(strPath, vList);
        }
        private string GetDefaultFileName()
        {
            string appdir = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), false, true);
            var    files  = Directory.GetFiles(appdir, @"pwned-passwords-ordered*.txt");

            if (files.Length == 0)
            {
                return("");
            }

            var latestFile = files[0];

            if (files.Length > 1)
            {
                DateTime maxCreationTime = File.GetLastWriteTime(latestFile);

                for (int i = 1; i < files.Length; i++)
                {
                    DateTime creationTime = File.GetLastWriteTime(files[i]);

                    if (creationTime > maxCreationTime)
                    {
                        maxCreationTime = creationTime;
                        latestFile      = files[i];
                    }
                }
            }

            return(Path.GetFullPath(latestFile));
        }
Example #13
0
        private static string GetFilename(string plugin, string lang)
        {
            string filename = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true, true);

            filename += KeePass.App.AppDefs.PluginsDir + UrlUtil.LocalDirSepChar + "Translations" + UrlUtil.LocalDirSepChar;
            filename += plugin + "." + lang + ".language.xml";
            return(filename);
        }
Example #14
0
        internal void LoadAllPlugins()
        {
            string[] vExclNames = new string[] {
                AppDefs.FileNames.Program, AppDefs.FileNames.XmlSerializers,
                AppDefs.FileNames.NativeLib32, AppDefs.FileNames.NativeLib64,
                AppDefs.FileNames.ShInstUtil
            };

            string strAppDir = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                        false, true);

            LoadAllPlugins(strAppDir, SearchOption.TopDirectoryOnly, vExclNames);
            g_strUserDir = strAppDir;             // Preliminary, see below

            if (WinUtil.IsAppX)
            {
                string str = UrlUtil.EnsureTerminatingSeparator(
                    AppConfigSerializer.AppDataDirectory, false) + AppDefs.PluginsDir;
                LoadAllPlugins(str, SearchOption.AllDirectories, vExclNames);

                g_strUserDir = str;
            }
            else if (!NativeLib.IsUnix())
            {
                string str = UrlUtil.EnsureTerminatingSeparator(strAppDir,
                                                                false) + AppDefs.PluginsDir;
                LoadAllPlugins(str, SearchOption.AllDirectories, vExclNames);

                g_strUserDir = str;
            }
            else             // Unix
            {
                try
                {
                    DirectoryInfo diPlgRoot = new DirectoryInfo(strAppDir);
                    foreach (DirectoryInfo diSub in diPlgRoot.GetDirectories())
                    {
                        if (diSub == null)
                        {
                            Debug.Assert(false); continue;
                        }

                        if (string.Equals(diSub.Name, AppDefs.PluginsDir,
                                          StrUtil.CaseIgnoreCmp))
                        {
                            LoadAllPlugins(diSub.FullName, SearchOption.AllDirectories,
                                           vExclNames);

                            g_strUserDir = diSub.FullName;
                        }
                    }
                }
                catch (Exception) { Debug.Assert(false); }
            }
        }
Example #15
0
        /// <summary>
        /// Common program initialization function that can also be
        /// used by applications that use KeePass as a library
        /// (like e.g. KPScript).
        /// </summary>
        public static bool CommonInit()
        {
            m_bDesignMode = false;             // Again, for the ones not calling Main

            int nRandomSeed = (int)DateTime.UtcNow.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            InitEnvSecurity();
            MonoWorkarounds.Initialize();

            // try { NativeMethods.SetProcessDPIAware(); }
            // catch(Exception) { }

            try { SelfTest.TestFipsComplianceProblems(); }
            catch (Exception exFips)
            {
                MessageService.ShowWarning(KPRes.SelfTestFailed, exFips);
                return(false);
            }

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            KdbxFile.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();

            m_appConfig.Apply(AceApplyFlags.All);

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            // InitEnvWorkarounds();
            LoadTranslation();

            CustomResourceManager.Override(typeof(KeePass.Properties.Resources));

            return(true);
        }
Example #16
0
		private static string GetKeyAssocID(IOConnectionInfo iocDb)
		{
			if(iocDb == null) throw new ArgumentNullException("iocDb");

			string strDb = iocDb.Path;
			if((strDb.Length > 0) && iocDb.IsLocalFile() &&
				!UrlUtil.IsAbsolutePath(strDb))
				strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);

			return strDb;
		}
Example #17
0
        private static void RunCSharpScript(string strScript)
        {
            string[] vUsing = CsUsing.Split(new string[] { "\r\n" },
                                            StringSplitOptions.None);
            string[] vClass = CsClass.Split(new string[] { "\r\n" },
                                            StringSplitOptions.None);
            int nLineOffset = vUsing.Length + vClass.Length;

            string str = CsUsing + CsClass + strScript + CsPost;

            CSharpCodeProvider cscp = new CSharpCodeProvider();

            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Deployment.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.ReferencedAssemblies.Add("System.Security.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = true;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors   = true;
            cp.WarningLevel            = 4;

            CompilerResults cr = cscp.CompileAssemblyFromSource(cp, str);

            if (cr.Errors.HasErrors)
            {
                StringBuilder sbErrors = new StringBuilder();
                foreach (CompilerError ce in cr.Errors)
                {
                    sbErrors.AppendLine((ce.Line - nLineOffset).ToString() +
                                        ": " + ce.ErrorText);
                }

                throw new Exception(sbErrors.ToString());
            }

            Assembly asm = cr.CompiledAssembly;

            Module m = asm.GetModules(false)[0];
            Type   t = m.GetType("KeePass.Scripting.ThisScript");

            t.GetMethod("Main").Invoke(null, null);

            File.Delete(cp.OutputAssembly);
        }
Example #18
0
        internal static void Init()
        {
            PluginsFolder             = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true, true);
            PluginsFolder             = UrlUtil.EnsureTerminatingSeparator(PluginsFolder + KeePass.App.AppDefs.PluginsDir, false);
            PluginsTranslationsFolder = UrlUtil.EnsureTerminatingSeparator(PluginsFolder + "Translations", false);
            m_sLastUpdateCheck        = KeePass.Program.Config.Application.LastUpdateCheck;
            List <string> lMsg = new List <string>();

            lMsg.Add("Plugins folder: " + PluginsFolder);
            lMsg.Add("Plugins translation folder: " + PluginsTranslationsFolder);
            lMsg.Add("Shieldify: " + Shieldify.ToString());
            lMsg.Add("Last update check: " + m_sLastUpdateCheck);
            PluginDebug.AddInfo("PluginUpdateHandler initialized", 0, lMsg.ToArray());
        }
Example #19
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Keyboard_Layout,
                                         KPRes.SelectLanguage, KPRes.SelectLanguageDesc);
            this.Icon = AppIcons.Default;
            this.Text = KPRes.SelectLanguage;

            UIUtil.SetExplorerTheme(m_lvLanguages, true);

            List <Image> lImg = new List <Image>();

            lImg.Add(Properties.Resources.B16x16_Browser);

            m_ilIcons = UIUtil.BuildImageListUnscaled(lImg,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));
            m_lvLanguages.SmallImageList = m_ilIcons;

            m_lvLanguages.Columns.Add(KPRes.AvailableLanguages);
            m_lvLanguages.Columns.Add(KPRes.Version);
            m_lvLanguages.Columns.Add(KPRes.Author);
            m_lvLanguages.Columns.Add(KPRes.Contact);

            ListViewItem lvi = m_lvLanguages.Items.Add("English", 0);

            lvi.SubItems.Add(PwDefs.VersionString);
            lvi.SubItems.Add(AppDefs.DefaultTrlAuthor);
            lvi.SubItems.Add(AppDefs.DefaultTrlContact);
            lvi.Tag = string.Empty;
            // UIUtil.SetFocusedItem(m_lvLanguages, lvi, true);

            // The configuration stores the file name only; filter duplicates
            List <string> lNames = new List <string>();

            GetAvailableTranslations(AppConfigSerializer.AppDataDirectory, lNames);
            GetAvailableTranslations(AppConfigSerializer.LocalAppDataDirectory, lNames);

            string strExe  = WinUtil.GetExecutable();
            string strPath = UrlUtil.GetFileDirectory(strExe, false, true);

            GetAvailableTranslations(strPath, lNames);

            UIUtil.ResizeColumns(m_lvLanguages, true);
            UIUtil.SetFocus(m_lvLanguages, this);
        }
Example #20
0
        private void BuildComponentsList(string strMainVersion)
        {
            string strValueColumn = KPRes.Version + "/" + KPRes.Status;

            if (Regex.IsMatch(strValueColumn, "\\s"))
            {
                strValueColumn = KPRes.Version + " / " + KPRes.Status;
            }

            m_lvComponents.Columns.Add(KPRes.Component, 100);
            m_lvComponents.Columns.Add(strValueColumn, 100);

            string strExe = WinUtil.GetExecutable();
            string strDir = UrlUtil.GetFileDirectory(strExe, true, false);

            AddComponentItem(PwDefs.ShortProductName, strMainVersion, strExe);

            string strXsl = UrlUtil.EnsureTerminatingSeparator(strDir +
                                                               AppDefs.XslFilesDir, false);
            bool b = File.Exists(strXsl + AppDefs.XslFileHtmlFull);

            b &= File.Exists(strXsl + AppDefs.XslFileHtmlLight);
            b &= File.Exists(strXsl + AppDefs.XslFileHtmlTabular);
            AddComponentItem(KPRes.XslStylesheetsKdbx, (b ? KPRes.Installed :
                                                        KPRes.NotInstalled), (b ? strXsl : null));

            b = KdbFile.IsLibraryInstalled();
            string strVer = (b ? (KdbManager.KeePassVersionString + " - 0x" +
                                  KdbManager.LibraryBuild.ToString("X4")) : KPRes.NotInstalled);
            string strPath = null;

            if (b)
            {
                string str = strDir + ((IntPtr.Size == 4) ? KdbManager.DllFile32 :
                                       KdbManager.DllFile64);
                if (File.Exists(str))
                {
                    strPath = str;
                }
                else
                {
                    Debug.Assert(false);
                }                                             // Somewhere else?
            }
            AddComponentItem(KPRes.KeePassLibCLong, strVer, strPath);
        }
Example #21
0
        private static void LoadTranslation()
        {
            string strLangFile = m_appConfig.Application.LanguageFile;

            if (string.IsNullOrEmpty(strLangFile))
            {
                return;
            }

            string[] vLangDirs = new string[] {
                AppConfigSerializer.AppDataDirectory,
                AppConfigSerializer.LocalAppDataDirectory,
                UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), false, false)
            };

            foreach (string strLangDir in vLangDirs)
            {
                string strLangPath = UrlUtil.EnsureTerminatingSeparator(
                    strLangDir, false) + strLangFile;

                try
                {
                    // Performance optimization
                    if (!File.Exists(strLangPath))
                    {
                        continue;
                    }

                    XmlSerializerEx xs = new XmlSerializerEx(typeof(KPTranslation));
                    m_kpTranslation = KPTranslation.Load(strLangPath, xs);

                    KPRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePass.Resources.KPRes"));
                    KLRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePassLib.Resources.KLRes"));

                    StrUtil.RightToLeft = m_kpTranslation.Properties.RightToLeft;
                    break;
                }
                // catch(DirectoryNotFoundException) { } // Ignore
                // catch(FileNotFoundException) { } // Ignore
                catch (Exception) { Debug.Assert(false); }
            }
        }
Example #22
0
        /// <summary>
        /// Common program initialization function that can also be
        /// used by applications that use KeePass as a library
        /// (like e.g. KPScript).
        /// </summary>
        public static bool CommonInit()
        {
            int nRandomSeed = (int)DateTime.UtcNow.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            InitEnvSecurity();

            try { SelfTest.TestFipsComplianceProblems(); }
            catch (Exception exFips)
            {
                MessageService.ShowWarning(KPRes.SelfTestFailed, exFips);
                return(false);
            }

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();
            IOConnection.SetProxy(m_appConfig.Integration.ProxyType,
                                  m_appConfig.Integration.ProxyAddress, m_appConfig.Integration.ProxyPort,
                                  m_appConfig.Integration.ProxyUserName, m_appConfig.Integration.ProxyPassword);

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            LoadTranslation();
            return(true);
        }
Example #23
0
		public void SetKeySources(IOConnectionInfo iocDb, CompositeKey cmpKey)
		{
			string strID = GetKeyAssocID(iocDb);
			int idx = GetKeyAssocIndex(strID);

			if((cmpKey == null) || !m_bRememberKeySources)
			{
				if(idx >= 0) m_vKeySources.RemoveAt(idx);
				return;
			}

			AceKeyAssoc a = new AceKeyAssoc();
			a.DatabasePath = strID;

			IUserKey kcpFile = cmpKey.GetUserKey(typeof(KcpKeyFile));
			if(kcpFile != null)
			{
				string strKeyFile = ((KcpKeyFile)kcpFile).Path;
				if(!string.IsNullOrEmpty(strKeyFile) && !StrUtil.IsDataUri(strKeyFile))
				{
					if(!UrlUtil.IsAbsolutePath(strKeyFile))
						strKeyFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(),
							strKeyFile);

					a.KeyFilePath = strKeyFile;
				}
			}

			IUserKey kcpCustom = cmpKey.GetUserKey(typeof(KcpCustomKey));
			if(kcpCustom != null)
				a.KeyProvider = ((KcpCustomKey)kcpCustom).Name;

			IUserKey kcpUser = cmpKey.GetUserKey(typeof(KcpUserAccount));
			a.UserAccount = (kcpUser != null);

			bool bAtLeastOne = ((a.KeyFilePath.Length > 0) ||
				(a.KeyProvider.Length > 0) || a.UserAccount);
			if(bAtLeastOne)
			{
				if(idx >= 0) m_vKeySources[idx] = a;
				else m_vKeySources.Add(a);
			}
			else if(idx >= 0) m_vKeySources.RemoveAt(idx);
		}
Example #24
0
        public bool InitEx()
        {
            try
            {
                string strDir = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                         false, true);
                List <string> l = UrlUtil.GetFilePaths(strDir, "*." +
                                                       KPTranslation.FileExtension, SearchOption.TopDirectoryOnly);
                if (l.Count != 0)
                {
                    string str = KPRes.LngInAppDir + MessageService.NewParagraph;

                    const int cMaxFL = 6;
                    for (int i = 0; i < Math.Min(l.Count, cMaxFL); ++i)
                    {
                        if (i == (cMaxFL - 1))
                        {
                            str += "...";
                        }
                        else
                        {
                            str += l[i];
                        }
                        str += MessageService.NewLine;
                    }
                    str += MessageService.NewLine;

                    str += KPRes.LngInAppDirNote + MessageService.NewParagraph;
                    str += KPRes.LngInAppDirQ;

                    if (MessageService.AskYesNo(str, PwDefs.ShortProductName, true,
                                                MessageBoxIcon.Warning))
                    {
                        WinUtil.OpenUrlDirectly(strDir);
                        return(false);
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(true);
        }
Example #25
0
        private static string GetPath()
        {
            if (m_strPath != null)
            {
                return(m_strPath);
            }

            string strBaseDir = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                         false, true);

            string[] vExes = Directory.GetFiles(strBaseDir, "WinSCP.com",
                                                SearchOption.AllDirectories);
            if ((vExes != null) && (vExes.Length >= 1))
            {
                m_strPath = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(),
                                                     vExes[0]);
            }

            return(m_strPath);
        }
Example #26
0
        internal static void CreateFile(string strXspFile, string strSourceDir)
        {
            try
            {
                string strExe = WinUtil.GetExecutable();

                string strFile = UrlUtil.MakeAbsolutePath(strExe, strXspFile);

                string strDir = UrlUtil.EnsureTerminatingSeparator(
                    strSourceDir, false);
                strDir = strDir.Substring(0, strDir.Length - 1);
                strDir = UrlUtil.EnsureTerminatingSeparator(
                    UrlUtil.MakeAbsolutePath(strExe, strDir), false);

                CreateFilePriv(strFile, strDir);
            }
            catch (Exception ex)
            {
                MessageService.ShowWarningExcp(ex);
            }
        }
Example #27
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            Debug.Assert(!m_lblCopyright.AutoSize);             // For RTL support
            m_lblCopyright.Text = PwDefs.Copyright + ".";

            string strTitle = PwDefs.ProductName;
            string strDesc  = KPRes.Version + " " + PwDefs.VersionString;

            if (Program.IsDevelopmentSnapshot())
            {
                strDesc += " (Dev.";
                try
                {
                    string   strExe = WinUtil.GetExecutable();
                    FileInfo fi     = new FileInfo(strExe);
                    strDesc += " " + fi.LastWriteTimeUtc.ToString("yyMMdd");
                }
                catch (Exception) { Debug.Assert(false); }
                strDesc += ")";
            }

            Icon icoSc = AppIcons.Get(AppIconType.Main, new Size(
                                          DpiUtil.ScaleIntX(48), DpiUtil.ScaleIntY(48)), Color.Empty);

            BannerFactory.CreateBannerEx(this, m_bannerImage, icoSc.ToBitmap(),
                                         strTitle, strDesc);
            this.Icon = AppIcons.Default;

            m_lvComponents.Columns.Add(KPRes.Component, 100, HorizontalAlignment.Left);
            m_lvComponents.Columns.Add(KPRes.Status + " / " + KPRes.Version, 100,
                                       HorizontalAlignment.Left);

            try { GetAppComponents(); }
            catch (Exception) { Debug.Assert(false); }

            UIUtil.SetExplorerTheme(m_lvComponents, false);
            UIUtil.ResizeColumns(m_lvComponents, true);
        }
Example #28
0
        private void GetAppComponents()
        {
            ListViewItem lvi = new ListViewItem(PwDefs.ShortProductName);

            lvi.SubItems.Add(PwDefs.VersionString);
            m_lvComponents.Items.Add(lvi);

            lvi = new ListViewItem(KPRes.XslStylesheetsKdbx);
            string strPath = WinUtil.GetExecutable();

            strPath  = UrlUtil.GetFileDirectory(strPath, true, false);
            strPath += AppDefs.XslFilesDir;
            strPath  = UrlUtil.EnsureTerminatingSeparator(strPath, false);
            bool bInstalled = File.Exists(strPath + AppDefs.XslFileHtmlFull);

            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlLight);
            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlTabular);
            if (!bInstalled)
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(KPRes.Installed);
            }
            m_lvComponents.Items.Add(lvi);

            lvi = new ListViewItem(KPRes.KeePassLibCLong);
            if (!KdbFile.IsLibraryInstalled())
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(KdbManager.KeePassVersionString + " (0x" +
                                 KdbManager.LibraryBuild.ToString("X4") + ")");
            }
            m_lvComponents.Items.Add(lvi);
        }
Example #29
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this, this);

            m_lblCopyright.Text = PwDefs.Copyright + ".";

            string strTitle = PwDefs.ProductName;
            string strDesc  = KPRes.Version + " " + PwDefs.VersionString;

            if (Program.IsDevelopmentSnapshot())
            {
                strDesc += " (Dev.";
                try
                {
                    string   strExe = WinUtil.GetExecutable();
                    FileInfo fi     = new FileInfo(strExe);
                    strDesc += " " + fi.LastWriteTimeUtc.ToString("yyMMdd");
                }
                catch (Exception) { Debug.Assert(false); }
                strDesc += ")";
            }

            Icon icoNew = new Icon(Properties.Resources.KeePass, 48, 48);

            BannerFactory.CreateBannerEx(this, m_bannerImage, icoNew.ToBitmap(),
                                         strTitle, strDesc);
            this.Icon = Properties.Resources.KeePass;

            m_lvComponents.Columns.Add(KPRes.Component, 100, HorizontalAlignment.Left);
            m_lvComponents.Columns.Add(KPRes.Status + " / " + KPRes.Version, 100,
                                       HorizontalAlignment.Left);

            try { GetAppComponents(); }
            catch (Exception) { Debug.Assert(false); }

            UIUtil.SetExplorerTheme(m_lvComponents, false);
            UIUtil.ResizeColumns(m_lvComponents, true);
        }
Example #30
0
        private static string GetMainVersion()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(PwDefs.VersionString);

            if (Program.IsDevelopmentSnapshot())
            {
                sb.Append(" - Dev.");

                try
                {
                    FileInfo fi      = new FileInfo(WinUtil.GetExecutable());
                    string   strDate = fi.LastWriteTimeUtc.ToString("yyMMdd");

                    sb.Append(' ');
                    sb.Append(strDate);
                }
                catch (Exception) { Debug.Assert(false); }
            }

            const string strParamPlh = @"{PARAM}";
            string       strBits     = KPRes.BitsA;

            if (strBits.IndexOf(strParamPlh) >= 0)
            {
                sb.Append(" (");
                sb.Append(strBits.Replace(strParamPlh, (IntPtr.Size * 8).ToString()));
                sb.Append(')');
            }
            else
            {
                Debug.Assert(false);
            }

            return(sb.ToString());
        }