private void MainWindow_FormLoadPost(object sender, EventArgs e)
        {
            HookOtherTimers(false);

            m_OtherTimers.Clear();
            if (m_lTimers.Contains("None"))
            {
                PluginDebug.AddInfo("Hooking other timers disabled", 0);
            }
            else
            {
                foreach (string sTimer in m_lTimers)
                {
                    string[] timer = sTimer.Split(new char[] { '.' }, 2);
                    if (timer.Length != 2)
                    {
                        PluginDebug.AddError("Invalid timer format", 0, "Expected: PluginNamespace.NameOfTimerVariable", "Found: " + sTimer);
                        continue;
                    }
                    AddTimerIfExists(timer[0], timer[1]);
                }
            }

            HookOtherTimers(true);
        }
Beispiel #2
0
            private int RemoveEmptyGroups(PwGroup pg)
            {
                int removed = 0;

                if (pg == null)
                {
                    return(removed);
                }
                for (int i = pg.Groups.Count() - 1; i >= 0; i--)
                {
                    PwGroup g = pg.Groups.GetAt((uint)i);
                    removed += RemoveEmptyGroups(g);
                    if ((g.Groups.UCount > 0) || (g.Entries.UCount > 0))
                    {
                        PluginDebug.AddError("Invalid group in OTP database", 0,
                                             "Group uuid: " + g.Uuid.ToHexString(),
                                             "Group name: " + g.Name,
                                             "Subgroups: " + g.Groups.UCount.ToString(),
                                             "Entries" + g.Entries.UCount.ToString());
                        continue;
                    }
                    pg.Groups.Remove(g);
                    removed++;
                }
                return(removed);
            }
        static Config()
        {
            if (KeePassLib.Native.NativeLib.IsUnix())
            {
                KPAutoTypePWPossible = false;
                return;
            }
            if (!Program.Config.CustomConfig.GetBool("AlternateAutoType.UseAutoTypePasswordHotKey", true))
            {
                return;
            }
            KPAutoTypePWPossible = Tools.KeePassVersion >= new Version(2, 41);
            if (!KPAutoTypePWPossible)
            {
                return;
            }
            m_piHotKeyGlobalAutoTypePassword = Program.Config.Integration.GetType().GetProperty("HotKeyGlobalAutoTypePassword");

            if (KPAutoTypePWPossible && (m_piHotKeyGlobalAutoTypePassword != null))
            {
                PluginDebug.AddInfo("Hooking Program.Config.Integration.HotKeyGlobalAutoTypePassword successful");
            }
            else
            {
                PluginDebug.AddError("Hooking Program.Config.Integration.HotKeyGlobalAutoTypePassword failed");
                KPAutoTypePWPossible = false;
            }
        }
Beispiel #4
0
        private void GetStandardMethods()
        {
            m_miUpdateColumnsEx = m_host.MainWindow.GetType().GetMethod("UpdateColumnsEx", BindingFlags.Instance | BindingFlags.NonPublic);
            if (m_miUpdateColumnsEx == null)
            {
                PluginDebug.AddError("Could not get method 'UpdateColumnsEx'", 0);
            }

            m_miGetEntryFieldEx = m_host.MainWindow.GetType().GetMethod("GetEntryFieldEx", BindingFlags.Instance | BindingFlags.NonPublic);
            if (m_miGetEntryFieldEx == null)
            {
                PluginDebug.AddError("Could not get method 'GetEntryFieldEx'", 0);
            }

            try
            {
                Type t = typeof(KeePass.Program).Assembly.GetType("KeePass.UI.AsyncPwListUpdate");
                m_miSprCompileFn = t.GetMethod("SprCompileFn", BindingFlags.Static | BindingFlags.NonPublic);
            }
            catch { }
            if (m_miSprCompileFn == null)
            {
                PluginDebug.AddError("Could not get method 'SprCompileFn'", 0);
            }
        }
Beispiel #5
0
        private void OnAutoTypeFormShown(object sender, EventArgs e)
        {
            AutoTypeCtxForm f  = sender as AutoTypeCtxForm;
            ListView        lv = Tools.GetControl("m_lvItems", f) as ListView;

            PluginDebug.AddInfo("Auto-Type entry selection window shown", 0);
            if ((lv != null) && (lv.Items.Count == 0) && !Program.Config.Integration.AutoTypeAlwaysShowSelDialog)
            {
                PluginDebug.AddInfo("Auto-Type Entry Selection window closed", 0, "Reason: No entries to display");
                f.Close();
                return;
            }
            if ((lv != null) && (lv.Items.Count == 1) && !Program.Config.Integration.AutoTypeAlwaysShowSelDialog)
            {
                lv.Items[0].Selected = true;
                try
                {
                    MethodInfo miPIS = f.GetType().GetMethod("ProcessItemSelection", BindingFlags.NonPublic | BindingFlags.Instance);
                    miPIS.Invoke(f, null);
                    PluginDebug.AddInfo("Auto-Type Entry Selection window closed", 0, "Reason: Only one entry to be shown");
                }
                catch (Exception ex)
                {
                    PluginDebug.AddError("Auto-Type Entry Selection window NOT closed", 0, "Reason: Could not process entry", "Details: " + ex.Message);
                }
                return;
            }
        }
Beispiel #6
0
        public override bool Initialize(IPluginHost host)
        {
            m_host = host;
            PluginTranslate.Init(this, KeePass.Program.Translation.Properties.Iso6391Code);
            Tools.DefaultCaption = PluginTranslate.PluginName;
            Tools.PluginURL      = "https://github.com/rookiestyle/coloredpassword/";

            m_menu        = new ToolStripMenuItem(Tools.DefaultCaption + "...");
            m_menu.Image  = SmallIcon;
            m_menu.Click += (o, e) => Tools.ShowOptions();
            m_host.MainWindow.ToolsMenu.DropDownItems.Add(m_menu);
            Tools.OptionsFormShown  += OptionsShown;
            Tools.OptionsFormClosed += OptionsClosed;

            ColorConfig.Read();
            m_lvEntries = (ListView)Tools.GetControl("m_lvEntries");
            if (m_lvEntries != null)
            {
                PluginDebug.AddSuccess("m_lvEntries found", 0);
                m_host.MainWindow.FormLoadPost += MainWindow_FormLoadPost;
            }
            else
            {
                PluginDebug.AddError("m_lvEntries not found", 0);
            }
            ColorPasswords(ColorConfig.Active);

            GlobalWindowManager.WindowAdded += OnWindowAdded;

            SinglePwDisplay.Enabled = ColorConfig.SinglePwDisplayActive;

            return(true);
        }
Beispiel #7
0
 private void SprEngine_FilterCompile(object sender, SprEventArgs e)
 {
     if ((e.Context.Flags & SprCompileFlags.ExtActive) != SprCompileFlags.ExtActive)
     {
         return;
     }
     if (e.Text.IndexOf(Config.Placeholder, StringComparison.InvariantCultureIgnoreCase) >= 0)
     {
         OTPDAO.EnsureOTPUsagePossible(e.Context.Entry);
         KPOTP myOTP = OTPDAO.GetOTP(e.Context.Entry);
         if (!myOTP.Valid)
         {
             PluginDebug.AddError("Auto-Type OTP failed", 0, "Uuid: " + e.Context.Entry.Uuid.ToHexString());
         }
         else
         {
             PluginDebug.AddInfo("Auto-Type OTP success", 0, "Uuid: " + e.Context.Entry.Uuid.ToHexString());
         }
         e.Text = StrUtil.ReplaceCaseInsensitive(e.Text, Config.Placeholder, myOTP.GetOTP(false, true));
         if (myOTP.Valid && (myOTP.Type == KPOTPType.HOTP))
         {
             var newOTP = myOTP.Clone();
             newOTP.HOTPCounter++;
             OTPDAO.SaveOTP(newOTP, e.Context.Entry);
         }
     }
 }
Beispiel #8
0
            public void OTPDB_Open()
            {
                if (m_bOpening)
                {
                    return;
                }
                m_bOpening = true;

                if (OTPDB_Opened)
                {
                    PluginDebug.AddInfo("OTP DB already opened");
                    UpdateDBHeader();
                    m_bOpening = false;
                    return;
                }
                if (!OTPDB_Exists)
                {
                    PluginDebug.AddError("OTP DB not available");
                    m_bOpening = false;
                    return;
                }

                OTPDB_Load();
                if (OTPDB_Opened)
                {
                    OTPDB.Modified = false;
                }
                m_bOpening = false;
            }
 private void HookOtherTimers(bool activate)
 {
     foreach (KeyValuePair <string, object> kvp in m_OtherTimers)
     {
         if (kvp.Value == null)
         {
             PluginDebug.AddError("Hook other timers", 2, "Object: " + kvp.Key, "Hook/Unhook: " + (activate ? "Hook" : "Unhook"), "Error: Object is null");
             return;
         }
         if (kvp.Value is System.Timers.Timer)
         {
             if (activate)
             {
                 (kvp.Value as System.Timers.Timer).Elapsed += OnUIStateUpdated;
             }
             else
             {
                 (kvp.Value as System.Timers.Timer).Elapsed -= OnUIStateUpdated;
             }
         }
         if (kvp.Value is Timer)
         {
             if (activate)
             {
                 (kvp.Value as Timer).Tick += OnUIStateUpdated;
             }
             else
             {
                 (kvp.Value as Timer).Tick -= OnUIStateUpdated;
             }
         }
         PluginDebug.AddSuccess("Hook other timers", 2, "Object: " + kvp.Key, "Hook/Unhook: " + (activate ? "Hook" : "Unhook"));
     }
 }
Beispiel #10
0
 //Format password profiles dependant on usage
 // - Used as PCA profile
 // - Used for generating the new password
 // - No special usage
 private void ctxPWGen_Opening(object sender, System.ComponentModel.CancelEventArgs e)
 {
     try
     {
         m_OnProfilesOpening(sender, e);
     }
     catch (Exception ex) { PluginDebug.AddError(ex.Message); }
 }
Beispiel #11
0
 public void SetDB(PwDatabase db)
 {
     m_db           = db;
     m_bInitialized = (db != null) && db.IsOpen;
     if (!m_bInitialized)
     {
         PluginDebug.AddError("Invalid DB provided");
     }
 }
Beispiel #12
0
        internal static void LoadPlugins(bool bReload)
        {
            lock (Plugins)             //Might be called in multiple threads, ensure a plugin is listed only once
            {
                if (!bReload && Plugins.Count > 0)
                {
                    return;
                }
                Plugins.Clear();
                if (m_Plugins.Count == 0)
                {
                    m_Plugins = Tools.GetLoadedPluginsName();
                }
                if (Plugins.Count > 0)
                {
                    return;                                    //Might have been filled from different thread meanwhile
                }
                List <string> lPluginnames = new List <string>();
                foreach (string sPlugin in m_Plugins.Keys)
                {
                    try
                    {
                        string s = sPlugin.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0];
                        Plugin p = (Plugin)Tools.GetPluginInstance(s);
                        if (p == null)
                        {
                            continue;
                        }

                        AssemblyCompanyAttribute[] comp = (AssemblyCompanyAttribute[])p.GetType().Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                        bool bOwnPlugin = string.Compare("rookiestyle", comp[0].Company, StringComparison.InvariantCultureIgnoreCase) == 0;

                        PluginUpdate pu = null;
                        if (bOwnPlugin)
                        {
                            pu = new OwnPluginUpdate(p.GetType().Namespace);
                        }
                        else
                        {
                            try { pu = new OtherPluginUpdate(p.GetType().Namespace); } catch { }
                        }
                        if (pu != null && Plugins.Find(x => x.Name == pu.Name) == null)
                        {
                            Plugins.Add(pu);
                            if (pu.UpdatePossible)
                            {
                                lPluginnames.Add(pu.Name);
                            }
                        }
                    }
                    catch (Exception ex) { PluginDebug.AddError(ex.Message, 0); }
                }
                PluginDebug.AddInfo("Installed updatable plugins", 0, lPluginnames.ToArray());
            }
        }
        public override bool Initialize(IPluginHost host)
        {
            Terminate();
            if (host == null)
            {
                return(false);
            }
            m_host = host;

            PluginTranslate.Init(this, Program.Translation.Properties.Iso6391Code);
            Tools.DefaultCaption = PluginTranslate.PluginName;
            Tools.PluginURL      = "https://github.com/rookiestyle/kpcolorchange/";

            PluginDebug.AddInfo("Display of expired entries: " + (Config.HideExpired ? "Hide" : "Show"), 1);
            m_lTimers = Config.GetOtherTimers();

            AddMenu();
            m_host.MainWindow.UIStateUpdated += OnUIStateUpdated;
            m_host.MainWindow.FormLoadPost   += MainWindow_FormLoadPost;

            Tools.OptionsFormShown      += OptionsFormShown;
            Tools.OptionsFormClosed     += OptionsFormClosed;
            m_host.MainWindow.KeyDown   += ToggleHideExpiredKey;
            m_host.MainWindow.KeyPreview = true;
            if (Config.ShowToolbarButton)
            {
                m_MainToolBar = (ToolStrip)Tools.GetControl("m_toolMain");
                if (m_MainToolBar != null)
                {
                    m_tsbToggle             = new ToolStripButton();
                    m_tsbToggle.Name        = "m_tbToggleExpired";
                    m_tsbToggle.ToolTipText = PluginTranslate.HideExpiredToolBar;
                    m_tsbToggle.Image       = SmallIcon;
                    m_tsbToggle.Click      += ToggleHideExpired;
                    m_tsbToggle.CheckState  = Config.HideExpired ? CheckState.Checked : CheckState.Unchecked;
                    m_tsbToggle.Checked     = Config.HideExpired;

                    m_MainToolBar.Items.Add(new ToolStripSeparator());
                    m_MainToolBar.Items.Add(m_tsbToggle);
                }
                else
                {
                    PluginDebug.AddError("Could not locate m_toolMain", 0);
                }
            }
            if (m_tsbToggle != null)
            {
                m_tsbToggle.Enabled = Config.AlreadyExpiredActive;
            }

            m_host.MainWindow.DocumentManager.ActiveDocumentSelected += HidingAllowedReset;
            PwGroup.GroupTouched += HidingAllowedReset;

            return(true);
        }
Beispiel #14
0
        private bool AddCheckBox(Form form)
        {
            CheckBox m_cbIgnoreGroupSettings = (CheckBox)Tools.GetControl("m_cbIgnoreGroupSettings", form);
            CheckBox m_cbDerefData           = (CheckBox)Tools.GetControl("m_cbDerefData", form);

            m_btnOK = (Button)Tools.GetControl("m_btnOK", form);
            Button btnCancel = (Button)Tools.GetControl("m_btnCancel", form);
            Button btnHelp   = (Button)Tools.GetControl("m_btnHelp", form);           //KeePass 2.47

            if ((m_cbIgnoreGroupSettings == null) || (m_cbDerefData == null) || (m_btnOK == null) || (btnCancel == null))
            {
                PluginDebug.AddError("Could not add 'Search in all DB' checkbox", 0,
                                     "m_cbIgnoreGroupSettings: " + (m_cbIgnoreGroupSettings == null).ToString(),
                                     "m_cbDerefData: " + (m_cbDerefData == null).ToString(),
                                     "m_btnOK: " + (m_btnOK == null).ToString(),
                                     "m_btnCancel: " + (btnCancel == null).ToString(),
                                     "m_btnHelp: " + (btnHelp == null).ToString());
                return(false);
            }
            m_cbSearchAllDatabases          = new CheckBox();
            m_cbSearchAllDatabases.Name     = "m_cbRookieSearchAllDB";
            m_cbSearchAllDatabases.Text     = PluginTranslate.Search;
            m_cbSearchAllDatabases.AutoSize = true;
            m_cbSearchAllDatabases.Left     = m_cbDerefData.Left;
            int spacing = m_cbDerefData.Top - m_cbIgnoreGroupSettings.Top;

            m_cbSearchAllDatabases.Top = m_cbDerefData.Top + spacing;
            Control c = m_cbDerefData.Parent;

            while (c != null)
            {
                c.Height += spacing;
                c         = c.Parent;
            }
            m_btnOK.Top   += spacing;
            btnCancel.Top += spacing;
            if (btnHelp != null)
            {
                btnHelp.Top += spacing;
            }
            m_cbDerefData.Parent.Controls.Add(m_cbSearchAllDatabases);
            PluginDebug.AddInfo("'Search db' checkbox added", 0);
            if (m_cbSearchAllDatabases.Enabled)
            {
                m_cbSearchAllDatabases.CheckedChanged += OnSelectAllDB_CheckedChanged;
            }
            else
            {
                PluginDebug.AddInfo("'Search db' checkbox is disabled, something went terribly wrong", 0);
                m_cbSearchAllDatabases.Enabled         = true;
                m_cbSearchAllDatabases.CheckedChanged += OnSelectAllDB_CheckedChanged;
            }
            return(true);
        }
Beispiel #15
0
        public override bool Initialize(IPluginHost host)
        {
            Terminate();
            if (host == null)
            {
                return(false);
            }
            m_host = host;

            PluginTranslate.Init(this, Program.Translation.Properties.Iso6391Code);
            Tools.DefaultCaption = PluginTranslate.PluginName;
            Tools.PluginURL      = "https://github.com/rookiestyle/keepassotp/";

            var t = typeof(Program).Assembly.GetType("KeePass.Native.NativeMethods");

            try { m_miSetForegroundWindowEx = t.GetMethod("SetForegroundWindowEx", BindingFlags.Static | BindingFlags.NonPublic); } catch { }
            if (m_miSetForegroundWindowEx == null)
            {
                PluginDebug.AddError("Could not locate method 'SetForegroundEx'", 0);
            }

            try { m_miGetForegroundWindowHandle = t.GetMethod("GetForegroundWindowHandle", BindingFlags.Static | BindingFlags.NonPublic); } catch { }
            if (m_miGetForegroundWindowHandle == null)
            {
                PluginDebug.AddError("Could not locate method 'GetForegroundWindowHandle'", 0);
            }

            m_miAutoType = m_host.MainWindow.GetType().GetMethod("ExecuteGlobalAutoType", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
            if (m_miSetForegroundWindowEx == null)
            {
                PluginDebug.AddError("Could not locate method 'ExecuteGlobalAutoType'", 0);
            }

            CreateMenu();
            AddTray();

            Config.Init();

            m_columnOTP = new KeePassOTPColumnProvider();
            m_host.ColumnProviderPool.Add(m_columnOTP);
            m_columnOTP.StartTimer();

            SprEngine.FilterCompile += SprEngine_FilterCompile;
            SprEngine.FilterPlaceholderHints.Add(Config.Placeholder);

            TFASites.Init(false);
            OTPDAO.Init();
            PTHotKeyManager.HotKeyPressed += PTHotKeyManager_HotKeyPressed;
            m_host.MainWindow.FileOpened  += MainWindow_FileOpened;

            GlobalWindowManager.WindowAdded += GlobalWindowManager_WindowAdded;

            return(true);
        }
Beispiel #16
0
            private bool OTPDB_Reload()
            {
                try
                {
                    byte[] bOTPDB = GetOTPDBData();
                    if (bOTPDB == null)
                    {
                        return(false);
                    }

                    //Create DB if required
                    if (!OTPDB_Exists)
                    {
                        SetDB(DB, true);
                    }
                    else if (!OTPDB_Opened)
                    {
                        if (Config.ShowHintSyncRequiresUnlock)
                        {
                            Tools.ShowInfo(PluginTranslate.HintSyncRequiresUnlock);
                        }
                        if (!EnsureOTPSetupPossible(null))
                        {
                            return(false);
                        }

                        //DB was not opened yet
                        //Try loading initially remembered database
                        //This is required to not lose local changes during a sync
                        //Current content of CustomData might already be replaced
                        if (!string.IsNullOrEmpty(m_sInitialOTPDB))
                        {
                            byte[] bInitial = ConvertFromCustomData(m_sInitialOTPDB);
                            m_sInitialOTPDB = string.Empty;
                            OTPDB_Synchronize(OTPDB, m_FFP, bInitial, PluginTranslate.OTPDB_Opening);
                        }
                    }
                    OTPDB_Synchronize(OTPDB, m_FFP, bOTPDB, PluginTranslate.OTPDB_Sync);
                    InitEntries(DB);
                    UpdateDBHeader();
                    PluginDebug.AddInfo("OTP db reloaded");
                    OTPDB_Opened = (OTPDB != null) && OTPDB.IsOpen;
                    if (OTPDB_Opened && CheckAndMigrate(DB))
                    {
                        FlagChanged(false);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    PluginDebug.AddError("Reloading OTP db failed", 0, ex.Message);
                    return(false);
                }
            }
Beispiel #17
0
        private static KPOTP ConvertOTPSettings(string settings)
        {
            KPOTP otp = new KPOTP();

            string[] setting = settings.ToUpper().Split(';');
            if (setting.Length != 5)
            {
                setting = new string[] { "30", "6", "TOTP", "BASE32", "SHA1" }
            }
            ;

            try
            {
                otp.Type = (KPOTPType)Enum.Parse(typeof(KPOTPType), setting[2]);
            }
            catch { PluginDebug.AddError("Invalid OTP data", 0, "Error field: Type", settings.ToUpper()); }
            try
            {
                otp.Encoding = (KPOTPEncoding)Enum.Parse(typeof(KPOTPEncoding), setting[3]);
            }
            catch { PluginDebug.AddError("Invalid OTP data", 0, "Error field: Encoding", settings.ToUpper()); }
            try
            {
                otp.Hash = (KPOTPHash)Enum.Parse(typeof(KPOTPHash), setting[4]);
            }
            catch { PluginDebug.AddError("Invalid OTP data", 0, "Error field: Hash", settings.ToUpper()); }

            int i = 0;

            if (!int.TryParse(setting[0], out i))
            {
                i = 30;
                PluginDebug.AddError("Invalid OTP data", 0, "Error field: Timestep / Counter", settings.ToUpper());
            }
            if (otp.Type == KPOTPType.TOTP)
            {
                otp.TOTPTimestep = i;
            }
            else
            {
                otp.HOTPCounter = i;
            }

            if (!int.TryParse(setting[1], out i))
            {
                i = 6;
                PluginDebug.AddError("Invalid OTP data", 0, "Error field: Length", settings.ToUpper());
            }
            otp.Length = i;
            return(otp);
        }
Beispiel #18
0
        /// <summary>
        /// Update installed plugin translations
        /// </summary>
        /// <param name="bDownloadActiveLanguage">Download translation for currently used language even if not installed yet</param>
        public void UpdatePluginTranslations(bool bDownloadActiveLanguage, List <string> lUpdateTranslations)
        {
            foreach (var upd in PluginUpdateHandler.Plugins)
            {
                upd.Selected = (lUpdateTranslations == null) || lUpdateTranslations.Contains(upd.Name);
            }
            bool bBackup = PluginConfig.DownloadActiveLanguage;

            PluginConfig.DownloadActiveLanguage = bDownloadActiveLanguage;

            //If called from CheckPluginLanguages, we're running in a different thread
            //Use Invoke because the IStatusLogger will attach to the KeyPromptForm within the UI thread
            m_host.MainWindow.Invoke(new KeePassLib.Delegates.GAction(() => { UpdatePlugins(true); }), null);
            PluginConfig.DownloadActiveLanguage = bBackup;
            foreach (var upd in PluginUpdateHandler.Plugins)
            {
                if (!upd.Selected)
                {
                    continue;
                }
                Plugin p = (Plugin)Tools.GetPluginInstance(upd.Name);
                if (p == null)
                {
                    continue;
                }
                Type t = p.GetType().Assembly.GetType("PluginTranslation.PluginTranslate");
                if (t == null)
                {
                    continue;
                }
                MethodInfo miInit = t.GetMethod("Init", BindingFlags.Static | BindingFlags.Public);
                if (miInit == null)
                {
                    continue;
                }
                try
                {
                    //Use Invoke because TranslationChangedEvent might be raised and can require running in UIThread
                    m_host.MainWindow.Invoke(new KeePassLib.Delegates.GAction(() =>
                    {
                        miInit.Invoke(p, new object[] { p, PluginUpdateHandler.LanguageIso });
                    }), null);
                }
                catch (Exception ex)
                {
                    PluginDebug.AddError("Refresh translation failed", 0, "Plugin: " + upd.Name, "Error: " + ex.Message);
                }
            }
            SetPluginSelectionStatus(false);
        }
Beispiel #19
0
 private void ColorPasswords(bool active)
 {
     if (!OverridePossible)
     {
         PluginDebug.AddError("TypeOverride not possible");
         return;
     }
     if (!KeePass.App.AppPolicy.Current.UnhidePasswords)
     {
         PluginDebug.AddError("Policy 'UnhidePasswords' does not allow unhiding passwords'");
         return;
     }
     if (ColorConfig.ColorEntryView)
     {
         if (m_lvEntries != null)
         {
             m_lvEntries.OwnerDraw = active;
             if (active)
             {
                 m_lvEntries.DrawColumnHeader += Lv_DrawColumnHeader;
                 m_lvEntries.DrawItem         += Lv_DrawItem;
                 m_lvEntries.DrawSubItem      += Lv_DrawSubItem;
             }
             else
             {
                 m_lvEntries.DrawColumnHeader -= Lv_DrawColumnHeader;
                 m_lvEntries.DrawItem         -= Lv_DrawItem;
                 m_lvEntries.DrawSubItem      -= Lv_DrawSubItem;
             }
             PluginDebug.AddInfo("m_lvEntries changed", "OwnerDraw: " + m_lvEntries.OwnerDraw.ToString(), "ColorPasswords active: " + active.ToString(), "Viewstyle: " + m_lvEntries.View.ToString());
         }
         else
         {
             PluginDebug.AddError("m_lvEntries cannot be changed");
         }
     }
     else
     {
         PluginDebug.AddInfo("ColorEntryView is disabled, check KeePass config file", 0);
     }
     if (active)
     {
         TypeOverridePool.Register(typeof(SecureTextBoxEx), CreateCustomInstance);
     }
     else
     {
         TypeOverridePool.Unregister(typeof(SecureTextBoxEx));
     }
 }
Beispiel #20
0
        private void HandleProfileSaveForm(SingleLineEditForm slef)
        {
            if (slef == null)
            {
                return;
            }

            //SingleLineEditForm is used multiple times
            //Check whether it's called from with the PwGeneratorForm
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
            if (st.GetFrames().SingleOrDefault(x => x.GetMethod().Name.Contains("OnBtnProfileSave")) == null)
            {
                return;
            }

            ComboBox cb = Tools.GetField("m_cmbEdit", slef) as ComboBox;

            if (cb == null)
            {
                PluginDebug.AddError("Cound not add 'Save db-specific' checkbox", 0, "m_cmbEdit not found");
                return;
            }
            CheckBox cbDB = new CheckBox();

            cbDB.Left = cb.Left;
            cbDB.Top  = DpiUtil.ScaleIntX(146);
            Button bOK = Tools.GetField("m_btnOK", slef) as Button;

            if (bOK != null)
            {
                cbDB.Top = bOK.Top + (int)((bOK.Height - cbDB.Height) / 2);
            }
            cbDB.Text            = PluginTranslate.SaveProfileInDB;
            cbDB.AutoSize        = true;
            cbDB.Enabled         = (m_host.Database != null) && m_host.Database.IsOpen;
            cbDB.CheckedChanged += AdjustProfileName;
            cb.Parent.SuspendLayout();
            cb.Parent.Controls.Add(cbDB);
            cb.Parent.ResumeLayout();
            cb.Parent.PerformLayout();

            cb.TextChanged += (o, e) =>
            {
                cbDB.CheckedChanged -= AdjustProfileName;
                cbDB.Checked         = cbDB.Enabled && (cb.Text.EndsWith(Config.ProfileDBOnly));
                cbDB.CheckedChanged += AdjustProfileName;
            };
        }
Beispiel #21
0
        public static void Init(Plugin plugin, string LanguageCodeIso6391)
        {
            List <string> lDebugStrings = new List <string>();

            m_translation.Clear();
            bool bError = true;

            LanguageCodeIso6391 = InitTranslation(plugin, lDebugStrings, LanguageCodeIso6391, out bError);
            if (bError && (LanguageCodeIso6391.Length > 2))
            {
                LanguageCodeIso6391 = LanguageCodeIso6391.Substring(0, 2);
                lDebugStrings.Add("Trying fallback: " + LanguageCodeIso6391);
                LanguageCodeIso6391 = InitTranslation(plugin, lDebugStrings, LanguageCodeIso6391, out bError);
            }
            if (bError)
            {
                PluginDebug.AddError("Reading translation failed", 0, lDebugStrings.ToArray());
                LanguageCodeIso6391 = "en";
            }
            else
            {
                List <FieldInfo> lTranslatable = new List <FieldInfo>(
                    typeof(PluginTranslate).GetFields(BindingFlags.Static | BindingFlags.Public)
                    ).FindAll(x => x.IsInitOnly);
                lDebugStrings.Add("Parsing complete");
                lDebugStrings.Add("Translated texts read: " + m_translation.Count.ToString());
                lDebugStrings.Add("Translatable texts: " + lTranslatable.Count.ToString());
                foreach (FieldInfo f in lTranslatable)
                {
                    if (m_translation.ContainsKey(f.Name))
                    {
                        lDebugStrings.Add("Key found: " + f.Name);
                        f.SetValue(null, m_translation[f.Name]);
                    }
                    else
                    {
                        lDebugStrings.Add("Key not found: " + f.Name);
                    }
                }
                PluginDebug.AddInfo("Reading translations finished", 0, lDebugStrings.ToArray());
            }
            if (TranslationChanged != null)
            {
                TranslationChanged(null, new TranslationChangedEventArgs(LanguageIso6391, LanguageCodeIso6391));
            }
            LanguageIso6391 = LanguageCodeIso6391;
            lDebugStrings.Clear();
        }
Beispiel #22
0
        public override bool Initialize(IPluginHost host)
        {
            m_host = host;
            PluginTranslate.Init(this, KeePass.Program.Translation.Properties.Iso6391Code);
            Tools.DefaultCaption = PluginTranslate.PluginName;
            Tools.PluginURL      = "https://github.com/rookiestyle/globalsearch/";

            GetStandardMethods();

            m_lvEntries = (ListView)Tools.GetControl("m_lvEntries");
            if (m_lvEntries == null)
            {
                PluginDebug.AddError("Could not get 'm_lvEntries'", 0);
            }

            Tools.OptionsFormShown  += Tools_OptionsFormShown;
            Tools.OptionsFormClosed += Tools_OptionsFormClosed;

            Activate();
            FindInfo fi = SearchHelp.FindList.Find(x => x.Name == SearchHelp.SearchForm);

            if (fi != null)
            {
                m_img = fi.img;
            }
            if (m_img == null)
            {
                try { m_img = (Image)KeePass.Program.Resources.GetObject("B16x16_XMag"); }
                catch { }
            }
            if (m_img == null)
            {
                m_img = m_host.MainWindow.ClientIcons.Images[(int)PwIcon.EMailSearch];
            }

            m_menu        = new ToolStripMenuItem();
            m_menu.Click += OnShowOptions;
            m_menu.Text   = PluginTranslate.PluginName + "...";
            m_menu.Image  = m_img;
            m_host.MainWindow.ToolsMenu.DropDownItems.Add(m_menu);

            return(true);
        }
Beispiel #23
0
 private bool CallStandardSearch(FindInfo fi, string sendername)
 {
     if (fi == null)
     {
         PluginDebug.AddError("Call standard find routine", 0, "Reason for standard call: FindInfo empty", "Event sender: " + sendername);
         return(true);
     }
     if (fi.StandardMethod == null)
     {
         PluginDebug.AddError("Call standard find routine", 0, "Action: " + fi.Name, "Reason for standard call: No hook for " + fi.Name);
         return(true);
     }
     if (m_host.MainWindow.DocumentManager.GetOpenDatabases().Count < 2)
     {
         PluginDebug.AddInfo("Call standard find routine", 0, "Action: " + fi.Name, "Reason for standard call: No more than one db opened");
         return(true);
     }
     return(false);
 }
Beispiel #24
0
        private void AddMenu()
        {
            PluginDebug.AddInfo("Add menu", 0);
            m_menu = new ToolStripMenuItem();
            m_menu.CheckOnClick    = true;
            m_menu.Checked         = Configuration.Active;
            m_menu.CheckedChanged += (o, e) => ToggleActive();
            m_menu.Image           = Configuration.Active ? m_iconActive : m_iconInactive;
            m_menu.Text            = Configuration.Active ? PluginTranslate.Active : PluginTranslate.Inactive;
            m_host.MainWindow.ToolsMenu.DropDownItems.Add(m_menu);

            m_host.MainWindow.EntryContextMenu.Opening += OnMenuOpening;
            m_ContextMenuEntry = CreatePEDMenu(false, false);
            m_MainMenuEntry    = CreatePEDMenu(false, false);

            m_host.MainWindow.GroupContextMenu.Opening += OnMenuOpening;
            m_ContextMenuGroup = CreatePEDMenu(true, false);
            m_MainMenuGroup    = CreatePEDMenu(true, false);

            PluginDebug.AddInfo("Add context menu");
            m_host.MainWindow.EntryContextMenu.Items.Insert(m_host.MainWindow.EntryContextMenu.Items.Count, m_ContextMenuEntry);
            m_host.MainWindow.GroupContextMenu.Items.Insert(m_host.MainWindow.GroupContextMenu.Items.Count, m_ContextMenuGroup);

            try
            {
                ToolStripMenuItem last = m_host.MainWindow.MainMenu.Items["m_menuGroup"] as ToolStripMenuItem;
                last.DropDownOpening += OnMenuOpening;
                last.DropDownItems.Add(m_MainMenuGroup);
                PluginDebug.AddInfo("Add group menu");

                last = m_host.MainWindow.MainMenu.Items["m_menuEntry"] as ToolStripMenuItem;
                last.DropDownOpening += OnMenuOpening;
                last.DropDownItems.Add(m_MainMenuEntry);
                PluginDebug.AddInfo("Add entry menu");
            }
            catch (Exception ex)
            {
                PluginDebug.AddError("Error adding menu", 0, ex.Message);
            }
        }
Beispiel #25
0
        private static bool MoveAllNonShieldified(string sTempFolder, string sTargetFolder)
        {
            bool          bSuccess = true;
            List <string> lFiles   = UrlUtil.GetFilePaths(sTempFolder, "*", SearchOption.AllDirectories);
            List <string> lMsg     = new List <string>();

            foreach (string sFile in m_lFilesDelete)
            {
                try     { File.Delete(sFile); }
                catch (Exception ex) { lMsg.Add(ex.Message); }
            }

            foreach (string sFile in lFiles)
            {
                string sTargetFile = sFile.Replace(sTempFolder, sTargetFolder);
                try { File.Copy(sFile, sTargetFile, true); }
                catch (Exception ex)
                {
                    bSuccess = false;
                    lMsg.Add(ex.Message);
                }
            }
            if (!bSuccess)
            {
                PluginDebug.AddError("Error moving files", 0, lMsg.ToArray());
                if (WinUtil.IsAtLeastWindowsVista)
                {
                    return(MoveAllShieldified(sTempFolder, sTargetFolder, true));
                }
                if (Tools.AskYesNo(PluginTranslate.PluginUpdateFailed, PluginTranslate.PluginUpdateCaption) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(sTempFolder);
                }
            }

            m_lFilesDelete.Clear();             //Clear list after MovAllShieldified was tried as well

            return(bSuccess);
        }
Beispiel #26
0
            private void OTPDB_Synchronize(PwDatabase targetdb, FileFormatProvider fmtImp, byte[] bDecrypted, string text)
            {
                IStatusLogger dlgStatus = new OnDemandStatusDialog(true, Program.MainForm);

                dlgStatus.StartLogging(text, false);
                try
                {
                    dlgStatus.SetText(text, LogStatusType.Info);

                    PwDatabase pwImp;
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), targetdb.MasterKey);
                    pwImp.MemoryProtection = targetdb.MemoryProtection.CloneDeep();
                    pwImp.MasterKey        = targetdb.MasterKey;

                    dlgStatus.SetText(text, LogStatusType.Info);

                    using (var s = new MemoryStream(bDecrypted))
                    {
                        fmtImp.Import(pwImp, s, null);
                    }
                    targetdb.KdfParameters   = pwImp.KdfParameters;
                    targetdb.DataCipherUuid  = pwImp.DataCipherUuid;
                    targetdb.HistoryMaxItems = pwImp.HistoryMaxItems;
                    targetdb.HistoryMaxSize  = pwImp.HistoryMaxSize;

                    PwMergeMethod mm = PwMergeMethod.Synchronize;

                    targetdb.RootGroup.Uuid = pwImp.RootGroup.Uuid;
                    targetdb.MergeIn(pwImp, mm, dlgStatus);
                    CleanupSyncedDB(targetdb);
                }
                catch (Exception ex)
                {
                    PluginDebug.AddError("Error loading OTP db", 0, ex.Message);
                    throw ex;
                }
                finally { dlgStatus.EndLogging(); }
            }
Beispiel #27
0
        private void AddSearchfield(AutoTypeCtxForm f)
        {
            var lvShownEntries = Tools.GetControl("m_lvItems", f) as ListView;

            if (lvShownEntries == null)
            {
                PluginDebug.AddError("Could not locate m_lvItems, search-as-you-type field not added");
                return;
            }
            var     c        = lvShownEntries.Parent;
            Label   lSearch  = new Label();
            TextBox tbSearch = new TextBox();

            c.Controls.Add(lSearch);
            c.Controls.Add(tbSearch);
            lSearch.Text     = KeePass.Resources.KPRes.FindEntries;
            lSearch.AutoSize = true;
            tbSearch.Left    = lvShownEntries.Left + lSearch.Width + DpiUtil.ScaleIntX(10);
            lSearch.Left     = lvShownEntries.Left;
            tbSearch.Top     = lvShownEntries.Top;
            lSearch.Top      = lvShownEntries.Top + tbSearch.Height / 2 - lSearch.Height / 2;
            tbSearch.Width   = lvShownEntries.Width / 2;
            List <ListViewItem> lvAllEntries = new List <ListViewItem>(lvShownEntries.Items.Cast <ListViewItem>());

            tbSearch.Tag = new _SearchAsYouTypeData()
            {
                AllEntries = lvAllEntries, ShownEntries = lvShownEntries
            };
            tbSearch.TextChanged += OnFilterSearchResults;
            int iGap    = DpiUtil.ScaleIntY(10);
            int iHeight = lvShownEntries.Height;

            tbSearch.Dock         = lvShownEntries.Dock = DockStyle.None;
            lvShownEntries.Top   += tbSearch.Height + iGap - 1;
            lvShownEntries.Height = iHeight - tbSearch.Height - iGap;
            lvShownEntries.Width  = lvShownEntries.Parent.ClientSize.Width - lvShownEntries.Parent.Padding.Left - lvShownEntries.Parent.Padding.Right;
        }
Beispiel #28
0
        //Color passwords in password generator
        private void OnPwGeneratorFormShown(object sender, EventArgs e)
        {
            (sender as Form).Shown -= OnPwGeneratorFormShown;
            if (!ColorConfig.Active)
            {
                return;
            }
            if (!ColorConfig.ColorPwGen)
            {
                return;
            }
            KeePass.Forms.PwGeneratorForm pg = sender as KeePass.Forms.PwGeneratorForm;
            TextBox tb = Tools.GetControl("m_tbPreview", pg) as TextBox;

            if (tb == null)
            {
                PluginDebug.AddError("Could not locate m_tbPreview", 0);
                return;
            }
            ColorTextBox rtb = new ColorTextBox();

            rtb.Name            = "ColoredPassword_" + tb.Name;
            rtb.Left            = tb.Left;
            rtb.Top             = tb.Top;
            rtb.Width           = tb.Width;
            rtb.Height          = tb.Height;
            rtb.ColorBackground = false;
            rtb.Multiline       = tb.Multiline;
            rtb.ReadOnly        = tb.ReadOnly;
            rtb.WordWrap        = tb.WordWrap;
            rtb.Font            = tb.Font;
            rtb.ScrollBars      = (RichTextBoxScrollBars)tb.ScrollBars;
            tb.Tag     = rtb;
            tb.Visible = false;
            tb.Parent.Controls.Add(rtb);
            tb.TextChanged += Tb_TextChanged;
        }
Beispiel #29
0
        internal static bool CopyOTP(PwEntry pe)
        {
            if (!OTPDAO.EnsureOTPUsagePossible(pe))
            {
                PluginDebug.AddError("Copy OTP failed", 0, "Uuid: " + pe.Uuid.ToHexString(), "OTP db not unlocked");
                return(false);
            }
            KPOTP myOTP = OTPDAO.GetOTP(pe);

            if (!myOTP.Valid)
            {
                PluginDebug.AddError("Copy OTP failed", 0, "Uuid: " + pe.Uuid.ToHexString());
                return(false);
            }
            ClipboardUtil.CopyAndMinimize(myOTP.GetOTP(false, true), true, Program.MainForm, pe, Program.MainForm.DocumentManager.SafeFindContainerOf(pe));
            Program.MainForm.StartClipboardCountdown();
            PluginDebug.AddInfo("Copy OTP success", 0, "Uuid: " + pe.Uuid.ToString());
            if (myOTP.Type == KPOTPType.HOTP)
            {
                myOTP.HOTPCounter++;
                OTPDAO.SaveOTP(myOTP, pe);
            }
            return(true);
        }
Beispiel #30
0
        private void UpdateAvailableTranslations()
        {
            Dictionary <string, List <UpdateComponentInfo> > dUpdateInfo = new Dictionary <string, List <UpdateComponentInfo> >();
            Dictionary <string, long> dResult = new Dictionary <string, long>();
            Type t = typeof(KeePass.Program).Assembly.GetType("KeePass.Util.UpdateCheckEx");

            if (t == null)
            {
                PluginDebug.AddError("Could not locate class 'UpdateCheckEx'", 0);
                return;
            }
            MethodInfo mi = t.GetMethod("DownloadInfoFiles", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Static);

            if (mi == null)
            {
                PluginDebug.AddError("Could not locate method 'DownloadInfoFiles'", 0);
                return;
            }

            if (string.IsNullOrEmpty(VersionURL))
            {
                PluginDebug.AddError("Could not read plugin update url", 0);
                return;
            }

            dUpdateInfo = mi.Invoke(null, new object[] { new List <string>()
                                                         {
                                                             VersionURL
                                                         }, null }) as Dictionary <string, List <UpdateComponentInfo> >;

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

            string[] cSplit = new string[] { "!", "!!!" };
            foreach (KeyValuePair <string, List <UpdateComponentInfo> > kvp in dUpdateInfo)
            {
                if (kvp.Value == null)
                {
                    continue;
                }
                Version vCheck = null;
                foreach (UpdateComponentInfo uci in kvp.Value)
                {
                    //Github: <Plugin>!<language identifier>
                    string[] sParts = uci.Name.Split(cSplit, StringSplitOptions.RemoveEmptyEntries);
                    if (sParts.Length == 1)
                    {
                        vCheck = new Version(StrUtil.VersionToString(uci.VerAvailable, 2));
                        if (VersionAvailableIsUnknown())
                        {
                            VersionAvailable = vCheck;
                        }
                    }
                    if (!PluginUpdateHandler.VersionsEqual(VersionInstalled, vCheck))
                    {
                        return;                                                                                   //Different version might require different translation files
                    }
                    if (sParts.Length != 2)
                    {
                        continue;
                    }
                    long lVer = 0;
                    if (!long.TryParse(StrUtil.VersionToString(uci.VerAvailable), out lVer))
                    {
                        continue;
                    }
                    string sLang = Name + "." + sParts[1].ToLowerInvariant() + ".language.xml";
                    TranslationVersionCheck tvc = Translations.Find(x => x.LangugageFile == sLang);
                    if (tvc == null)
                    {
                        tvc = new TranslationVersionCheck()
                        {
                            LangugageFile = sLang
                        };
                        Translations.Add(tvc);
                    }
                    tvc.Available = lVer;
                }
            }
        }