Beispiel #1
0
 public static string RunConsoleApp(string strAppPath, string strParams)
 {
     return(NativeLib.RunConsoleApp(strAppPath, strParams));
 }
Beispiel #2
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            // Can be invoked by tray command; don't use CenterParent
            Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen);

            // When multiline is enabled, tabs added by plugins can result
            // in multiple tab rows, cropping the tab content at the bottom;
            // https://sourceforge.net/p/keepass/discussion/329220/thread/a17a2734/
            Debug.Assert(!m_tabMain.Multiline);

            GlobalWindowManager.AddWindow(this);

            this.Icon = AppIcons.Default;

            Debug.Assert(m_ilIcons != null);
            if (m_ilIcons != null)
            {
                m_tabMain.ImageList = m_ilIcons;

                m_tabSecurity.ImageIndex    = (int)PwIcon.TerminalEncrypted;
                m_tabPolicy.ImageIndex      = (int)PwIcon.List;
                m_tabGui.ImageIndex         = (int)PwIcon.Screen;
                m_tabIntegration.ImageIndex = (int)PwIcon.Console;
                m_tabAdvanced.ImageIndex    = (int)PwIcon.ClipboardReady;
            }

            uint uTab = Program.Config.Defaults.OptionsTabIndex;

            if (uTab < (uint)m_tabMain.TabPages.Count)
            {
                m_tabMain.SelectedTab = m_tabMain.TabPages[(int)uTab];
            }

            m_aceUrlSchemeOverrides = Program.Config.Integration.UrlSchemeOverrides.CloneDeep();
            m_strUrlOverrideAll     = Program.Config.Integration.UrlOverride;

            Debug.Assert(!m_cmbMenuStyle.Sorted);
            m_cmbMenuStyle.Items.Add(KPRes.Auto + " (" + KPRes.Recommended + ")");
            m_cmbMenuStyle.Items.Add(new string('-', 24));
            int nTsrs = 2, iTsrSel = 0, nSuffixes = 0;

            foreach (TsrFactory fTsr in TsrPool.Factories)
            {
                string strSuffix = string.Empty;
                if (!fTsr.IsSupported())
                {
                    strSuffix = " (" + KPRes.IncompatibleEnv + ")";
                    ++nSuffixes;
                }

                string strUuid = Convert.ToBase64String(fTsr.Uuid.UuidBytes);
                if (Program.Config.UI.ToolStripRenderer == strUuid)
                {
                    iTsrSel = nTsrs;
                }

                m_cmbMenuStyle.Items.Add((fTsr.Name ?? string.Empty) + strSuffix);
                m_dTsrUuids[nTsrs] = strUuid;
                ++nTsrs;
            }
            Debug.Assert(m_cmbMenuStyle.Items.Count == nTsrs);
            m_cmbMenuStyle.SelectedIndex = iTsrSel;
            if (nSuffixes > 0)
            {
                m_cmbMenuStyle.DropDownWidth = m_cmbMenuStyle.Width * 2;
            }
            if (AppConfigEx.IsOptionEnforced(Program.Config.UI, "ToolStripRenderer"))
            {
                m_lblMenuStyle.Enabled = false;
                m_cmbMenuStyle.Enabled = false;
            }

            Debug.Assert(!m_cmbBannerStyle.Sorted);
            m_cmbBannerStyle.Items.Add("(" + KPRes.CurrentStyle + ")");
            m_cmbBannerStyle.Items.Add("Windows XP Login");
            m_cmbBannerStyle.Items.Add("Windows Vista Black");
            m_cmbBannerStyle.Items.Add("KeePass Win32");
            m_cmbBannerStyle.Items.Add("Blue Carbon");

            CreateDialogBanner(BannerStyle.Default);             // Default forces generation
            m_cmbBannerStyle.SelectedIndex = (int)BannerStyle.Default;
            if ((BannerFactory.CustomGenerator != null) ||
                AppConfigEx.IsOptionEnforced(Program.Config.UI, "BannerStyle"))
            {
                m_lblBannerStyle.Enabled = false;
                m_cmbBannerStyle.Enabled = false;
            }

            int nWidth = m_lvPolicy.ClientSize.Width - UIUtil.GetVScrollBarWidth();

            m_lvPolicy.Columns.Add(KPRes.Feature, (nWidth * 10) / 29);
            m_lvPolicy.Columns.Add(KPRes.Description, (nWidth * 19) / 29);

            m_hkGlobalAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                                m_tbGlobalAutoType, false);
            m_hkSelectedAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                                  m_tbSelAutoTypeHotKey, false);
            m_hkShowWindow = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                            m_tbShowWindowHotKey, false);

            if (!NativeLib.IsUnix())
            {
                UIUtil.SetShield(m_btnFileExtCreate, true);
                UIUtil.SetShield(m_btnFileExtRemove, true);

                m_linkHotKeyHelp.Visible = false;
            }
            else             // Unix
            {
                m_hkGlobalAutoType.TextNone   = KPRes.External;
                m_hkSelectedAutoType.TextNone = KPRes.External;
                m_hkShowWindow.TextNone       = KPRes.External;

                m_hkGlobalAutoType.Enabled = m_hkSelectedAutoType.Enabled =
                    m_hkShowWindow.Enabled = false;
                m_btnFileExtCreate.Enabled = m_btnFileExtRemove.Enabled = false;
                m_cbAutoRun.Enabled        = false;
            }

            UIUtil.SetExplorerTheme(m_lvSecurityOptions, false);
            UIUtil.SetExplorerTheme(m_lvPolicy, false);
            UIUtil.SetExplorerTheme(m_lvGuiOptions, false);
            UIUtil.SetExplorerTheme(m_lvAdvanced, false);

            AppConfigEx.ClearXmlPathCache();

            LoadOptions();

            // if(Program.Config.Meta.IsEnforcedConfiguration)
            //	m_lvPolicy.Enabled = false;

            UpdateUIState();
        }
Beispiel #3
0
        private void LoadSecurityOptions()
        {
            AceWorkspaceLocking aceWL = Program.Config.Security.WorkspaceLocking;

            uint uLockTime = aceWL.LockAfterTime;
            bool bLockTime = (uLockTime > 0);

            m_numLockAfterTime.Value  = (bLockTime ? uLockTime : 300);
            m_cbLockAfterTime.Checked = bLockTime;
            if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterTime"))
            {
                m_cbLockAfterTime.Enabled = false;
            }

            uLockTime = aceWL.LockAfterGlobalTime;
            bLockTime = (uLockTime > 0);
            m_numLockAfterGlobalTime.Value  = (bLockTime ? uLockTime : 240);
            m_cbLockAfterGlobalTime.Checked = bLockTime;
            if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterGlobalTime"))
            {
                m_cbLockAfterGlobalTime.Enabled = false;
            }

            int nDefaultExpireDays = Program.Config.Defaults.NewEntryExpiresInDays;

            if (nDefaultExpireDays < 0)
            {
                m_cbDefaultExpireDays.Checked = false;
            }
            else
            {
                m_cbDefaultExpireDays.Checked = true;
                try { m_numDefaultExpireDays.Value = nDefaultExpireDays; }
                catch (Exception) { Debug.Assert(false); }
            }
            if (AppConfigEx.IsOptionEnforced(Program.Config.Defaults, "NewEntryExpiresInDays"))
            {
                m_cbDefaultExpireDays.Enabled = false;
            }

            int nClipClear = Program.Config.Security.ClipboardClearAfterSeconds;

            if (nClipClear >= 0)
            {
                m_cbClipClearTime.Checked = true;
                m_numClipClearTime.Value  = nClipClear;
            }
            else
            {
                m_cbClipClearTime.Checked = false;
            }
            if (AppConfigEx.IsOptionEnforced(Program.Config.Security, "ClipboardClearAfterSeconds"))
            {
                m_cbClipClearTime.Enabled = false;
            }

            m_lvSecurityOptions.Columns.Add(string.Empty);             // Resize below

            ListViewGroup lvg = new ListViewGroup(KPRes.Options);

            m_lvSecurityOptions.Groups.Add(lvg);
            Debug.Assert(lvg.ListView == m_lvSecurityOptions);

            m_cdxSecurityOptions = new CheckedLVItemDXList(m_lvSecurityOptions, true);

            bool?  obNoSEv      = null;       // Allow read-only by enforced config
            string strSEvSuffix = string.Empty;

            if (MonoWorkarounds.IsRequired(1378))
            {
                obNoSEv      = true;
                strSEvSuffix = " (" + KPRes.UnsupportedByMono + ")";
            }

            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnWindowMinimize",
                                            lvg, KPRes.LockOnMinimizeTaskbar);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnWindowMinimizeToTray",
                                            lvg, KPRes.LockOnMinimizeTray);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSessionSwitch",
                                            lvg, KPRes.LockOnSessionSwitch + strSEvSuffix, obNoSEv);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSuspend",
                                            lvg, KPRes.LockOnSuspend + strSEvSuffix, obNoSEv);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnRemoteControlChange",
                                            lvg, KPRes.LockOnRemoteControlChange + strSEvSuffix, obNoSEv);
            m_cdxSecurityOptions.CreateItem(aceWL, "ExitInsteadOfLockingAfterTime",
                                            lvg, KPRes.ExitInsteadOfLockingAfterTime);
            m_cdxSecurityOptions.CreateItem(aceWL, "AlwaysExitInsteadOfLocking",
                                            lvg, KPRes.ExitInsteadOfLockingAlways);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClipboardClearOnExit",
                                            lvg, KPRes.ClipboardClearOnExit);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security,
                                            "UseClipboardViewerIgnoreFormat", lvg,
                                            KPRes.ClipboardViewerIgnoreFormat + " " + KPRes.NotRecommended);

            if (NativeLib.IsLibraryInstalled())
            {
                m_cdxSecurityOptions.CreateItem(Program.Config.Native, "NativeKeyTransformations",
                                                lvg, KPRes.NativeLibUse);
            }

            bool?obNoWin = null;              // Allow read-only by enforced config

            if (NativeLib.IsUnix())
            {
                obNoWin = true;
            }

            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "MasterKeyOnSecureDesktop",
                                            lvg, KPRes.MasterKeyOnSecureDesktop, obNoWin);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClearKeyCommandLineParams",
                                            lvg, KPRes.ClearKeyCmdLineParams);

            m_cdxSecurityOptions.UpdateData(false);
            UIUtil.ResizeColumns(m_lvSecurityOptions, true);
        }
        public static bool Copy(byte[] pbToCopy, string strFormat, bool bEncode,
                                bool bIsEntryInfo, IntPtr hOwner)
        {
            Debug.Assert(pbToCopy != null);
            if (pbToCopy == null)
            {
                throw new ArgumentNullException("pbToCopy");
            }

            if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
            {
                return(false);
            }

            string strEnc = null;

            try
            {
                if (bEncode || NativeLib.IsUnix())
                {
                    strEnc = StrUtil.DataToDataUri(pbToCopy,
                                                   ClipFmtToMimeType(strFormat));
                }

                if (!NativeLib.IsUnix())                // Windows
                {
                    if (!OpenW(hOwner, true))
                    {
                        throw new InvalidOperationException();
                    }

                    uint uFormat = NativeMethods.RegisterClipboardFormat(strFormat);

                    bool bFailed = false;
                    if (!AttachIgnoreFormatW())
                    {
                        bFailed = true;
                    }

                    if (!bEncode)
                    {
                        if (!SetDataW(uFormat, pbToCopy))
                        {
                            bFailed = true;
                        }
                    }
                    else                     // Encode
                    {
                        if (!SetDataW(uFormat, strEnc, false))
                        {
                            bFailed = true;
                        }
                    }

                    CloseW();

                    if (bFailed)
                    {
                        return(false);
                    }
                }
                else if (NativeLib.GetPlatformID() == PlatformID.MacOSX)
                {
                    SetStringM(strEnc);
                }
                else if (NativeLib.IsUnix())
                {
                    SetStringU(strEnc);
                }
                // else // Managed, no encoding
                // {
                //	Clear();
                //	DataObject doData = CreateProtectedDataObject(strFormat, pbToCopy);
                //	Clipboard.SetDataObject(doData);
                // }
            }
            catch (Exception) { Debug.Assert(false); return(false); }

            m_strFormat = strFormat;
            m_bEncoded  = (strEnc != null);

            // if(strEnc != null)
            //	m_pbDataHash32 = CryptoUtil.HashSha256(StrUtil.Utf8.GetBytes(strEnc));
            // else
            m_pbDataHash32 = CryptoUtil.HashSha256(pbToCopy);

            RaiseCopyEvent(bIsEntryInfo, string.Empty);

            return(true);
        }
Beispiel #5
0
        public static bool PerformIntoCurrentWindow(PwEntry pe, PwDatabase pdContext,
                                                    string strSeq)
        {
            if (pe == null)
            {
                Debug.Assert(false); return(false);
            }
            if (!pe.GetAutoTypeEnabled())
            {
                return(false);
            }
            if (!AppPolicy.Try(AppPolicyId.AutoTypeWithoutContext))
            {
                return(false);
            }

            Thread.Sleep(TargetActivationDelay);

            IntPtr hWnd;
            string strWindow;

            try
            {
                NativeMethods.GetForegroundWindowInfo(out hWnd, out strWindow, true);
            }
            catch (Exception) { hWnd = IntPtr.Zero; strWindow = null; }

            if (!NativeLib.IsUnix())
            {
                if (strWindow == null)
                {
                    Debug.Assert(false); return(false);
                }
            }
            else
            {
                strWindow = string.Empty;
            }

            if (strSeq == null)
            {
                SequenceQueriesEventArgs evQueries = GetSequencesForWindowBegin(
                    hWnd, strWindow);

                List <string> lSeq = GetSequencesForWindow(pe, hWnd, strWindow,
                                                           pdContext, evQueries.EventID);

                GetSequencesForWindowEnd(evQueries);

                if (lSeq.Count == 0)
                {
                    strSeq = pe.GetAutoTypeSequence();
                }
                else
                {
                    strSeq = lSeq[0];
                }
            }

            AutoTypeCtx ctx = new AutoTypeCtx(strSeq, pe, pdContext);

            return(AutoType.PerformInternal(ctx, strWindow));
        }
Beispiel #6
0
        public static Image GetImageForPath(string strPath, Size?osz,
                                            bool bAllowCache, bool bNewImageObject)
        {
            if (strPath == null)
            {
                Debug.Assert(false); strPath = string.Empty;
            }
            Size sz = GetSizeOrSmall(osz);

            Image img       = null;
            bool  bImgIsNew = false;

            string strKey = GetCacheItemKey(FiTypePath, strPath, sz);

            if (bAllowCache && g_dCache.TryGetValue(strKey, out img))
            {
                if (bNewImageObject)
                {
                    img = (img.Clone() as Image);
                }
                return(img);
            }
            Debug.Assert(img == null);

            if (strPath.Length == 0)
            {
                img       = Properties.Resources.B16x16_Binary;
                bImgIsNew = false;
            }

            try
            {
                if ((img == null) && !NativeLib.IsUnix())
                {
                    string strDisplayName;
                    NativeMethods.SHGetFileInfo(strPath, sz.Width, sz.Height,
                                                out img, out strDisplayName);
                    bImgIsNew = true;
                }
            }
            catch (Exception) { Debug.Assert(false); }

            if ((img == null) && !MonoWorkarounds.IsRequired(100003))
            {
                img       = UIUtil.GetFileIcon(strPath, sz.Width, sz.Height);
                bImgIsNew = true;
            }

            if (img == null)
            {
                BinaryDataClass bdc = BinaryDataClassifier.ClassifyUrl(strPath);

                if ((bdc == BinaryDataClass.Text) || (bdc == BinaryDataClass.RichText))
                {
                    img = Properties.Resources.B16x16_ASCII;
                }
                else if (bdc == BinaryDataClass.Image)
                {
                    img = Properties.Resources.B16x16_Spreadsheet;
                }
                else if (bdc == BinaryDataClass.WebDocument)
                {
                    img = Properties.Resources.B16x16_HTML;
                }
                else if (strPath.EndsWith(".exe", StrUtil.CaseIgnoreCmp))
                {
                    img = Properties.Resources.B16x16_Make_KDevelop;
                }
                else
                {
                    img = Properties.Resources.B16x16_Binary;
                }

                bImgIsNew = false;
            }

            if (img == null)
            {
                Debug.Assert(false); return(null);
            }

            if ((img.Width != sz.Width) || (img.Height != sz.Height))
            {
                Image imgSc = GfxUtil.ScaleImage(img, sz.Width, sz.Height,
                                                 ScaleTransformFlags.UIIcon);
                if (bImgIsNew)
                {
                    img.Dispose();
                }
                img = imgSc;
            }

            if (bAllowCache)
            {
                g_dCache[strKey] = img;
            }

            if (bNewImageObject && (bAllowCache || !bImgIsNew))
            {
                img = (img.Clone() as Image);
            }

            return(img);
        }
Beispiel #7
0
        private static byte[] OpenExternal(string strName, byte[] pbData,
                                           BinaryDataOpenOptions opt)
        {
            byte[] pbResult = null;

            try
            {
                string strBaseTempDir = UrlUtil.EnsureTerminatingSeparator(
                    UrlUtil.GetTempPath(), false);

                string strTempID, strTempDir;
                while (true)
                {
                    byte[] pbRandomID = CryptoRandom.Instance.GetRandomBytes(8);
                    strTempID = Convert.ToBase64String(pbRandomID);
                    strTempID = StrUtil.AlphaNumericOnly(strTempID);
                    if (strTempID.Length == 0)
                    {
                        Debug.Assert(false); continue;
                    }

                    strTempDir = strBaseTempDir + strTempID;
                    if (!Directory.Exists(strTempDir))
                    {
                        Directory.CreateDirectory(strTempDir);

                        strTempDir = UrlUtil.EnsureTerminatingSeparator(
                            strTempDir, false);

                        // Mark directory as encrypted, such that new files
                        // are encrypted automatically; there exists no
                        // Directory.Encrypt method, but we can use File.Encrypt,
                        // because this internally uses the EncryptFile API
                        // function, which works with directories
                        try { File.Encrypt(strTempDir); }
                        catch (Exception) { Debug.Assert(false); }

                        break;
                    }
                }

                strName = UrlUtil.GetSafeFileName(strName);

                string strFile = strTempDir + strName;
                File.WriteAllBytes(strFile, pbData);

                // Encrypt again, in case the directory encryption above failed
                try { File.Encrypt(strFile); }
                catch (Exception) { Debug.Assert(false); }

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName         = NativeLib.EncodePath(strFile);
                psi.UseShellExecute  = true;
                psi.WorkingDirectory = strTempDir;

                ParameterizedThreadStart pts = new ParameterizedThreadStart(
                    BinaryDataUtil.ShellOpenFn);
                Thread th = new Thread(pts);
                th.Start(psi);

                string strMsgMain = KPRes.AttachExtOpened + MessageService.NewParagraph +
                                    KPRes.AttachExtOpenedPost + ":";
                string strMsgImp        = KPRes.Import;
                string strMsgImpDesc    = KPRes.AttachExtImportDesc;
                string strMsgCancel     = KPRes.DiscardChangesCmd;
                string strMsgCancelDesc = KPRes.AttachExtDiscardDesc;

                VistaTaskDialog vtd = new VistaTaskDialog();
                vtd.CommandLinks    = true;
                vtd.Content         = strMsgMain;
                vtd.MainInstruction = strName;
                vtd.WindowTitle     = PwDefs.ShortProductName;
                vtd.SetIcon(VtdCustomIcon.Question);

                vtd.AddButton((int)DialogResult.OK, strMsgImp, strMsgImpDesc);
                vtd.AddButton((int)DialogResult.Cancel, strMsgCancel, strMsgCancelDesc);

                vtd.FooterText = KPRes.AttachExtSecDel;
                vtd.SetFooterIcon(VtdIcon.Information);

                bool bImport;
                if (vtd.ShowDialog())
                {
                    bImport = ((vtd.Result == (int)DialogResult.OK) ||
                               (vtd.Result == (int)DialogResult.Yes));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(strName);
                    sb.AppendLine();
                    sb.AppendLine(strMsgMain);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.Yes + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgImp) +
                                  " - " + strMsgImpDesc);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.No + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgCancel) +
                                  " - " + strMsgCancelDesc);
                    sb.AppendLine();
                    sb.AppendLine(KPRes.AttachExtSecDel);

                    bImport = MessageService.AskYesNo(sb.ToString());
                }

                if (bImport && !opt.ReadOnly)
                {
                    while (true)
                    {
                        try
                        {
                            pbResult = File.ReadAllBytes(strFile);
                            break;
                        }
                        catch (Exception exRead)
                        {
                            if (!AskForRetry(strFile, exRead.Message))
                            {
                                break;
                            }
                        }
                    }
                }

                string strReportObj = null;
                while (true)
                {
                    try
                    {
                        strReportObj = strFile;
                        if (File.Exists(strFile))
                        {
                            FileInfo fiTemp = new FileInfo(strFile);
                            long     cb     = fiTemp.Length;
                            if (cb > 0)
                            {
                                byte[] pbOvr = new byte[cb];
                                Program.GlobalRandom.NextBytes(pbOvr);
                                File.WriteAllBytes(strFile, pbOvr);
                            }

                            File.Delete(strFile);
                        }

                        strReportObj = strTempDir;
                        if (Directory.Exists(strTempDir))
                        {
                            Directory.Delete(strTempDir, true);
                        }

                        break;
                    }
                    catch (Exception exDel)
                    {
                        if (!AskForRetry(strReportObj, exDel.Message))
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            return(pbResult);
        }
Beispiel #8
0
        public static void Main(string[] args)
        {
#if DEBUG
            // Program.DesignMode should not be queried before executing
            // Main (e.g. by a static Control) when running the program
            // normally
            Debug.Assert(!m_bDesignModeQueried);
#endif
            m_bDesignMode = false;             // Designer doesn't call Main method

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();             // Required

#if DEBUG
            string strInitialWorkDir = WinUtil.GetWorkingDirectory();
#endif

            if (!CommonInit())
            {
                CommonTerminate(); return;
            }

            if (m_appConfig.Application.Start.PluginCacheClearOnce)
            {
                PlgxCache.Clear();
                m_appConfig.Application.Start.PluginCacheClearOnce = false;
                AppConfigSerializer.Save(Program.Config);
            }

            m_cmdLineArgs = new CommandLineArgs(args);

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null)
            {
                // All important .NET assemblies are in memory now already
                try { SelfTest.Perform(); }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }

            /* else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            else if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                     (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null)
            {
                MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString());
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null)
            {
                XmlSerializerEx.GenerateSerializers(m_cmdLineArgs);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null)
            {
                Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString);
                Console.WriteLine(PwDefs.Copyright);
                MainCleanUp();
                return;
            }
            // #if (DEBUG && !KeePassLibSD)
            // else if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            // {
            //	PopularPasswords.MakeList();
            //	MainCleanUp();
            //	return;
            // }
            // #endif

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Exit);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoType);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null)
            {
                string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid];
                if (!string.IsNullOrEmpty(strEntryUuid))
                {
                    IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl,
                                                      strEntryUuid, null, null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipUrl);
                }

                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent] != null)
            {
                string strName = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent];
                if (!string.IsNullOrEmpty(strName))
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipEvent = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName,
                                                        CommandLineArgs.SafeSerialize(vFlt), null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipEvent);
                }

                MainCleanUp();
                return;
            }

            // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);
            bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true);
            // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            UserActivityNotifyFilter nfActivity = new UserActivityNotifyFilter();
            Application.AddMessageFilter(nfActivity);

#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
            {
                throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
            }

            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
                {
                    throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
                }

                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg)
            {
                // Catch message box exception;
                // https://sourceforge.net/p/keepass/patches/86/
                try { MessageService.ShowFatal(exPrg); }
                catch (Exception) { Console.Error.WriteLine(exPrg.ToString()); }
            }
#endif

            Application.RemoveMessageFilter(nfActivity);

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

#if DEBUG
            string strEndWorkDir = WinUtil.GetWorkingDirectory();
            Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp));
#endif

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); }
        }
Beispiel #9
0
        private static bool Execute(AutoTypeCtx ctx)
        {
            if (ctx == null)
            {
                Debug.Assert(false); return(false);
            }

            string  strSeq  = ctx.Sequence;
            PwEntry pweData = ctx.Entry;

            if (pweData == null)
            {
                Debug.Assert(false); return(false);
            }

            if (!pweData.GetAutoTypeEnabled())
            {
                return(false);
            }
            if (!AppPolicy.Try(AppPolicyId.AutoType))
            {
                return(false);
            }

            if (NativeLib.IsUnix())
            {
                if (!NativeMethods.TryXDoTool() && !NativeLib.IsWayland())
                {
                    MessageService.ShowWarning(KPRes.AutoTypeXDoToolRequired,
                                               KPRes.PackageInstallHint);
                    return(false);
                }
            }

            PwDatabase pwDatabase = ctx.Database;

            bool bObfuscate = (pweData.AutoType.ObfuscationOptions !=
                               AutoTypeObfuscationOptions.None);
            AutoTypeEventArgs args = new AutoTypeEventArgs(strSeq, bObfuscate,
                                                           pweData, pwDatabase);

            if (AutoType.FilterCompilePre != null)
            {
                AutoType.FilterCompilePre(null, args);
            }

            args.Sequence = SprEngine.Compile(args.Sequence, new SprContext(
                                                  pweData, pwDatabase, SprCompileFlags.All, true, false));

            // string strError = ValidateAutoTypeSequence(args.Sequence);
            // if(!string.IsNullOrEmpty(strError))
            // {
            //	MessageService.ShowWarning(args.Sequence +
            //		MessageService.NewParagraph + strError);
            //	return false;
            // }

            Application.DoEvents();

            if (AutoType.FilterSendPre != null)
            {
                AutoType.FilterSendPre(null, args);
            }
            if (AutoType.FilterSend != null)
            {
                AutoType.FilterSend(null, args);
            }

            if (args.Sequence.Length > 0)
            {
                string strError = null;
                try { SendInputEx.SendKeysWait(args.Sequence, args.SendObfuscated); }
                catch (SecurityException exSec) { strError = exSec.Message; }
                catch (Exception ex)
                {
                    strError = args.Sequence + MessageService.NewParagraph +
                               ex.Message;
                }

                if (AutoType.SendPost != null)
                {
                    AutoType.SendPost(null, args);
                }

                if (!string.IsNullOrEmpty(strError))
                {
                    try
                    {
                        MainForm mfP = Program.MainForm;
                        if (mfP != null)
                        {
                            mfP.EnsureVisibleForegroundWindow(false, false);
                        }
                    }
                    catch (Exception) { Debug.Assert(false); }

                    MessageService.ShowWarning(strError);
                }
            }

            pweData.Touch(false);
            EntryUtil.ExpireTanEntryIfOption(pweData, pwDatabase);

            MainForm mf = Program.MainForm;

            if (mf != null)
            {
                // Always refresh entry list (e.g. {NEWPASSWORD} might
                // have changed data)
                mf.RefreshEntriesList();

                // SprEngine.Compile might have modified the database;
                // pd.Modified is set by SprEngine
                mf.UpdateUI(false, null, false, null, false, null, false);

                if (Program.Config.MainWindow.MinimizeAfterAutoType &&
                    mf.IsCommandTypeInvokable(null, MainForm.AppCommandType.Window))
                {
                    UIUtil.SetWindowState(mf, FormWindowState.Minimized);
                }
            }

            return(true);
        }
Beispiel #10
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            // Can be invoked by tray command; don't use CenterParent
            Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen);

            GlobalWindowManager.AddWindow(this);

            this.Icon = Properties.Resources.KeePass;

            Debug.Assert(m_ilIcons != null);
            if (m_ilIcons != null)
            {
                m_tabMain.ImageList = m_ilIcons;

                m_tabSecurity.ImageIndex    = (int)PwIcon.TerminalEncrypted;
                m_tabPolicy.ImageIndex      = (int)PwIcon.List;
                m_tabGui.ImageIndex         = (int)PwIcon.Screen;
                m_tabIntegration.ImageIndex = (int)PwIcon.Console;
                m_tabAdvanced.ImageIndex    = (int)PwIcon.ClipboardReady;
            }

            uint uTab = Program.Config.Defaults.OptionsTabIndex;

            if (uTab < (uint)m_tabMain.TabPages.Count)
            {
                m_tabMain.SelectedTab = m_tabMain.TabPages[(int)uTab];
            }

            m_aceUrlSchemeOverrides = Program.Config.Integration.UrlSchemeOverrides.CloneDeep();

            m_cmbBannerStyle.Items.Add("(" + KPRes.CurrentStyle + ")");
            m_cmbBannerStyle.Items.Add("WinXP Login");
            m_cmbBannerStyle.Items.Add("WinVista Black");
            m_cmbBannerStyle.Items.Add("KeePass Win32");
            m_cmbBannerStyle.Items.Add("Blue Carbon");

            CreateDialogBanner(BannerStyle.Default);             // Default forces generation
            m_cmbBannerStyle.SelectedIndex = (int)BannerStyle.Default;
            if ((BannerFactory.CustomGenerator != null) ||
                AppConfigEx.IsOptionEnforced(Program.Config.UI, "BannerStyle"))
            {
                m_lblBannerStyle.Enabled = false;
                m_cmbBannerStyle.Enabled = false;
            }

            int nWidth = m_lvPolicy.ClientRectangle.Width - UIUtil.GetVScrollBarWidth() - 1;

            m_lvPolicy.Columns.Add(KPRes.Feature, (nWidth * 10) / 29);
            m_lvPolicy.Columns.Add(KPRes.Description, (nWidth * 19) / 29);

            m_hkGlobalAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                                m_tbGlobalAutoType, false);
            m_hkSelectedAutoType = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                                  m_tbSelAutoTypeHotKey, false);
            m_hkShowWindow = HotKeyControlEx.ReplaceTextBox(m_grpHotKeys,
                                                            m_tbShowWindowHotKey, false);

            if (!NativeLib.IsUnix())
            {
                UIUtil.SetShield(m_btnFileExtCreate, true);
                UIUtil.SetShield(m_btnFileExtRemove, true);

                m_linkHotKeyHelp.Visible = false;
            }
            else             // Unix
            {
                Program.Config.Integration.HotKeyGlobalAutoType   = (ulong)Keys.None;
                Program.Config.Integration.HotKeySelectedAutoType = (ulong)Keys.None;
                Program.Config.Integration.HotKeyShowWindow       = (ulong)Keys.None;

                m_hkGlobalAutoType.Enabled = m_hkSelectedAutoType.Enabled =
                    m_hkShowWindow.Enabled = false;
                m_btnFileExtCreate.Enabled = m_btnFileExtRemove.Enabled = false;
                m_cbAutoRun.Enabled        = false;
            }

            UIUtil.SetExplorerTheme(m_lvSecurityOptions, false);
            UIUtil.SetExplorerTheme(m_lvPolicy, false);
            UIUtil.SetExplorerTheme(m_lvGuiOptions, false);
            UIUtil.SetExplorerTheme(m_lvAdvanced, false);

            AppConfigEx.ClearXmlPathCache();

            LoadOptions();

            // if(Program.Config.Meta.IsEnforcedConfiguration)
            //	m_lvPolicy.Enabled = false;

            UpdateUIState();
        }
Beispiel #11
0
        private void LoadSecurityOptions()
        {
            AceWorkspaceLocking aceWL = Program.Config.Security.WorkspaceLocking;

            uint uLockTime = aceWL.LockAfterTime;
            bool bLockTime = (uLockTime > 0);

            m_numLockAfterTime.Value  = (bLockTime ? uLockTime : 300);
            m_cbLockAfterTime.Checked = bLockTime;
            if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterTime"))
            {
                m_cbLockAfterTime.Enabled = false;
            }

            uLockTime = aceWL.LockAfterGlobalTime;
            bLockTime = (uLockTime > 0);
            m_numLockAfterGlobalTime.Value  = (bLockTime ? uLockTime : 240);
            m_cbLockAfterGlobalTime.Checked = bLockTime;
            if (AppConfigEx.IsOptionEnforced(aceWL, "LockAfterGlobalTime"))
            {
                m_cbLockAfterGlobalTime.Enabled = false;
            }

            int nDefaultExpireDays = Program.Config.Defaults.NewEntryExpiresInDays;

            if (nDefaultExpireDays < 0)
            {
                m_cbDefaultExpireDays.Checked = false;
            }
            else
            {
                m_cbDefaultExpireDays.Checked = true;
                try { m_numDefaultExpireDays.Value = nDefaultExpireDays; }
                catch (Exception) { Debug.Assert(false); }
            }
            if (AppConfigEx.IsOptionEnforced(Program.Config.Defaults, "NewEntryExpiresInDays"))
            {
                m_cbDefaultExpireDays.Enabled = false;
            }

            int nClipClear = Program.Config.Security.ClipboardClearAfterSeconds;

            if (nClipClear >= 0)
            {
                m_cbClipClearTime.Checked = true;
                m_numClipClearTime.Value  = nClipClear;
            }
            else
            {
                m_cbClipClearTime.Checked = false;
            }
            if (AppConfigEx.IsOptionEnforced(Program.Config.Security, "ClipboardClearAfterSeconds"))
            {
                m_cbClipClearTime.Enabled = false;
            }

            m_lvSecurityOptions.Columns.Add(string.Empty, 200);             // Resize below

            ListViewGroup lvg = new ListViewGroup(KPRes.Options);

            m_lvSecurityOptions.Groups.Add(lvg);
            Debug.Assert(lvg.ListView == m_lvSecurityOptions);

            m_cdxSecurityOptions = new CheckedLVItemDXList(m_lvSecurityOptions, true);

            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnWindowMinimize",
                                            lvg, KPRes.LockOnMinimize);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSessionSwitch",
                                            lvg, KPRes.LockOnSessionSwitch);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnSuspend",
                                            lvg, KPRes.LockOnSuspend);
            m_cdxSecurityOptions.CreateItem(aceWL, "LockOnRemoteControlChange",
                                            lvg, KPRes.LockOnRemoteControlChange);
            m_cdxSecurityOptions.CreateItem(aceWL, "ExitInsteadOfLockingAfterTime",
                                            lvg, KPRes.ExitInsteadOfLockingAfterTime);
            m_cdxSecurityOptions.CreateItem(aceWL, "AlwaysExitInsteadOfLocking",
                                            lvg, KPRes.ExitInsteadOfLockingAlways);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClipboardClearOnExit",
                                            lvg, KPRes.ClipboardClearOnExit);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security,
                                            "UseClipboardViewerIgnoreFormat", lvg,
                                            KPRes.ClipboardViewerIgnoreFormat + " " + KPRes.NotRecommended);

            if (NativeLib.IsLibraryInstalled())
            {
                m_cdxSecurityOptions.CreateItem(Program.Config.Native, "NativeKeyTransformations",
                                                lvg, KPRes.NativeLibUse);
            }

            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "MasterKeyOnSecureDesktop",
                                            lvg, KPRes.MasterKeyOnSecureDesktop);
            m_cdxSecurityOptions.CreateItem(Program.Config.Security, "ClearKeyCommandLineParams",
                                            lvg, KPRes.ClearKeyCmdLineParams);

            m_cdxSecurityOptions.UpdateData(false);
            m_lvSecurityOptions.Columns[0].Width = m_lvSecurityOptions.ClientRectangle.Width -
                                                   UIUtil.GetVScrollBarWidth() - 1;
        }
Beispiel #12
0
        /* private static void OnHotKey(string strKey, IntPtr lpUserData)
         * {
         *      if(string.IsNullOrEmpty(strKey)) return;
         *      if(strKey.IndexOf(@"<Release>", StrUtil.CaseIgnoreCmp) >= 0) return;
         *
         *      if(m_fRecvWnd != null)
         *      {
         *              MainForm mf = (m_fRecvWnd as MainForm);
         *              if(mf == null) { Debug.Assert(false); return; }
         *
         *              Keys k = EggAccStringToKeys(strKey);
         *              foreach(KeyValuePair<int, Keys> kvp in m_vRegKeys)
         *              {
         *                      if(kvp.Value == k) mf.HandleHotKey(kvp.Key);
         *              }
         *      }
         *      else { Debug.Assert(false); }
         * }
         *
         * private static Keys EggAccStringToKeys(string strKey)
         * {
         *      if(string.IsNullOrEmpty(strKey)) return Keys.None;
         *
         *      Keys k = Keys.None;
         *
         *      if(strKey.IndexOf(@"<Alt>", StrUtil.CaseIgnoreCmp) >= 0)
         *              k |= Keys.Alt;
         *      if((strKey.IndexOf(@"<Ctl>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Ctrl>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Control>", StrUtil.CaseIgnoreCmp) >= 0))
         *              k |= Keys.Control;
         *      if((strKey.IndexOf(@"<Shft>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Shift>", StrUtil.CaseIgnoreCmp) >= 0))
         *              k |= Keys.Shift;
         *
         *      string strKeyCode = strKey;
         *      while(strKeyCode.IndexOf('<') >= 0)
         *      {
         *              int nStart = strKeyCode.IndexOf('<');
         *              int nEnd = strKeyCode.IndexOf('>');
         *              if((nStart < 0) || (nEnd < 0) || (nEnd <= nStart)) { Debug.Assert(false); break; }
         *
         *              strKeyCode = strKeyCode.Remove(nStart, nEnd - nStart + 1);
         *      }
         *      strKeyCode = strKeyCode.Trim();
         *
         *      try { k |= (Keys)Enum.Parse(typeof(Keys), strKeyCode, true); }
         *      catch(Exception) { Debug.Assert(false); }
         *
         *      return k;
         * }
         *
         * private static string EggAccKeysToString(Keys k)
         * {
         *      StringBuilder sb = new StringBuilder();
         *
         *      if((k & Keys.Shift) != Keys.None) sb.Append(@"<Shift>");
         *      if((k & Keys.Control) != Keys.None) sb.Append(@"<Control>");
         *      if((k & Keys.Alt) != Keys.None) sb.Append(@"<Alt>");
         *
         *      sb.Append((k & Keys.KeyCode).ToString());
         *      return sb.ToString();
         * } */

        internal static void CheckCtrlAltA(Form fParent)
        {
            try
            {
                if (!Program.Config.Integration.CheckHotKeys)
                {
                    return;
                }
                if (NativeLib.IsUnix())
                {
                    return;
                }

                // Check for a conflict only in the very specific case of
                // Ctrl+Alt+A; in all other cases we assume that the user
                // is aware of a possible conflict and intentionally wants
                // to override any system key combination
                if (Program.Config.Integration.HotKeyGlobalAutoType !=
                    (ulong)(Keys.Control | Keys.Alt | Keys.A))
                {
                    return;
                }

                // Check for a conflict only on Polish systems; other
                // languages typically don't use Ctrl+Alt+A frequently
                // and a conflict warning would just be confusing for
                // most users
                IntPtr hKL        = NativeMethods.GetKeyboardLayout(0);
                ushort uLangID    = (ushort)(hKL.ToInt64() & 0xFFFFL);
                ushort uPriLangID = NativeMethods.GetPrimaryLangID(uLangID);
                if (uPriLangID != NativeMethods.LANG_POLISH)
                {
                    return;
                }

                int vk = (int)Keys.A;

                // We actually check for RAlt (which maps to Ctrl+Alt)
                // instead of LCtrl+LAlt
                byte[] pbState = new byte[256];
                pbState[NativeMethods.VK_CONTROL]  = 0x80;
                pbState[NativeMethods.VK_LCONTROL] = 0x80;
                pbState[NativeMethods.VK_MENU]     = 0x80;
                pbState[NativeMethods.VK_RMENU]    = 0x80;
                pbState[NativeMethods.VK_NUMLOCK]  = 0x01;                // Toggled
                // pbState[vk] = 0x80;

                string strUni = NativeMethods.ToUnicode3(vk, pbState, IntPtr.Zero);
                if (string.IsNullOrEmpty(strUni))
                {
                    return;
                }
                if (strUni.EndsWith("a") || strUni.EndsWith("A"))
                {
                    return;
                }

                if (char.IsControl(strUni, 0))
                {
                    Debug.Assert(false); strUni = "?";
                }

                string str = KPRes.CtrlAltAConflict.Replace(@"{PARAM}", strUni) +
                             MessageService.NewParagraph + KPRes.CtrlAltAConflictHint;

                VistaTaskDialog dlg = new VistaTaskDialog();
                dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
                dlg.CommandLinks    = false;
                dlg.Content         = str;
                dlg.DefaultButtonID = (int)DialogResult.Cancel;
                dlg.MainInstruction = KPRes.KeyboardKeyCtrl + "+" +
                                      KPRes.KeyboardKeyAlt + "+A - " + KPRes.Warning;
                dlg.SetIcon(VtdIcon.Warning);
                dlg.VerificationText = KPRes.DialogNoShowAgain;
                dlg.WindowTitle      = PwDefs.ShortProductName;

                if (dlg.ShowDialog(fParent))
                {
                    if (dlg.ResultVerificationChecked)
                    {
                        Program.Config.Integration.CheckHotKeys = false;
                    }
                }
                else
                {
                    MessageService.ShowWarning(str);
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Beispiel #13
0
        public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo,
                                PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner)
        {
            if (strToCopy == null)
            {
                throw new ArgumentNullException("strToCopy");
            }

            if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
            {
                return(false);
            }

            string strData = (bSprCompile ? SprEngine.Compile(strToCopy,
                                                              new SprContext(peEntryInfo, pwReferenceSource,
                                                                             SprCompileFlags.All)) : strToCopy);

            try
            {
                if (!NativeLib.IsUnix())                // Windows
                {
                    if (!OpenW(hOwner, true))
                    {
                        throw new InvalidOperationException();
                    }

                    bool bFailed = false;
                    if (!AttachIgnoreFormatW())
                    {
                        bFailed = true;
                    }
                    if (!SetDataW(null, strData, null))
                    {
                        bFailed = true;
                    }
                    CloseW();

                    if (bFailed)
                    {
                        return(false);
                    }
                }
                else if (NativeLib.GetPlatformID() == PlatformID.MacOSX)
                {
                    SetStringM(strData);
                }
                else if (NativeLib.IsUnix())
                {
                    SetStringU(strData);
                }
                // else // Managed
                // {
                //	Clear();
                //	DataObject doData = CreateProtectedDataObject(strData);
                //	Clipboard.SetDataObject(doData);
                // }
            }
            catch (Exception) { Debug.Assert(false); return(false); }

            m_strFormat = null;

            byte[]        pbUtf8 = StrUtil.Utf8.GetBytes(strData);
            SHA256Managed sha256 = new SHA256Managed();

            m_pbDataHash32 = sha256.ComputeHash(pbUtf8);

            RaiseCopyEvent(bIsEntryInfo, strData);

            if (peEntryInfo != null)
            {
                peEntryInfo.Touch(false);
            }

            // SprEngine.Compile might have modified the database
            MainForm mf = Program.MainForm;

            if ((mf != null) && bSprCompile)
            {
                mf.RefreshEntriesList();
                mf.UpdateUI(false, null, false, null, false, null, false);
            }

            return(true);
        }
Beispiel #14
0
        private static void ExportEntry(PwEntry pe, string strDir, PwExportInfo pxi)
        {
            PwDatabase pd  = ((pxi != null) ? pxi.ContextDatabase : null);
            SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive, false, false);

            KeyValuePair <string, string>?okvpCmd = null;
            string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), ctx);

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                strUrl = WinUtil.GetCommandLineFromUrl(strUrl);

                if (!NativeLib.IsUnix())                // LNKs only supported on Windows
                {
                    string strApp, strArgs;
                    StrUtil.SplitCommandLine(strUrl, out strApp, out strArgs);

                    if (!string.IsNullOrEmpty(strApp))
                    {
                        okvpCmd = new KeyValuePair <string, string>(strApp, strArgs);
                    }
                }
            }
            if (string.IsNullOrEmpty(strUrl))
            {
                return;
            }
            bool bLnk = okvpCmd.HasValue;

            string strTitleCmp = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.TitleField), ctx);

            if (string.IsNullOrEmpty(strTitleCmp))
            {
                strTitleCmp = KPRes.Entry;
            }
            string strTitle = Program.Config.Defaults.WinFavsFileNamePrefix + strTitleCmp;

            string strSuffix = Program.Config.Defaults.WinFavsFileNameSuffix +
                               (bLnk ? ".lnk" : ".url");

            strSuffix = UrlUtil.FilterFileName(strSuffix);

            string strFileBase = (UrlUtil.EnsureTerminatingSeparator(strDir,
                                                                     false) + UrlUtil.FilterFileName(strTitle));
            string strFile = strFileBase + strSuffix;
            int    iFind   = 2;

            while (File.Exists(strFile))
            {
                strFile = strFileBase + " (" + iFind.ToString() + ")" + strSuffix;
                ++iFind;
            }

            if (!Directory.Exists(strDir))
            {
                try { Directory.CreateDirectory(strDir); }
                catch (Exception exDir)
                {
                    throw new Exception(strDir + MessageService.NewParagraph + exDir.Message);
                }

                WaitForDirCommit(strDir, true);
            }

            try
            {
                if (bLnk)
                {
                    int    ccMaxDesc = NativeMethods.INFOTIPSIZE - 1 - LnkDescSuffix.Length;
                    string strDesc   = StrUtil.CompactString3Dots(strUrl, ccMaxDesc) +
                                       LnkDescSuffix;

                    ShellLinkEx sl = new ShellLinkEx(okvpCmd.Value.Key,
                                                     okvpCmd.Value.Value, strDesc);
                    sl.Save(strFile);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(@"[InternetShortcut]");
                    sb.AppendLine(@"URL=" + strUrl);                     // No additional line break
                    sb.AppendLine(@"[" + PwDefs.ShortProductName + @"]");
                    sb.AppendLine(IniTypeKey + @"=" + IniTypeValue);
                    // Terminating line break is important

                    File.WriteAllText(strFile, sb.ToString(), Encoding.Default);
                }
            }
            catch (Exception exWrite)
            {
                throw new Exception(strFile + MessageService.NewParagraph + exWrite.Message);
            }
        }
        // https://www.fileformat.info/tip/microsoft/enter_unicode.htm
        // https://sourceforge.net/p/keepass/feature-requests/2180/
        private bool HandleAltX(KeyEventArgs e, bool bDown)
        {
            // Rich text boxes of Windows already support Alt+X
            if (!NativeLib.IsUnix())
            {
                return(false);
            }

            if (!e.Control && e.Alt && (e.KeyCode == Keys.X))
            {
            }
            else
            {
                return(false);
            }

            UIUtil.SetHandled(e, true);
            if (!bDown)
            {
                return(true);
            }

            try
            {
                string strSel = (this.SelectedText ?? string.Empty);
                int    iSel   = this.SelectionStart;
                Debug.Assert(this.SelectionLength == strSel.Length);

                if (e.Shift)                // Character -> code
                {
                    string strChar = strSel;
                    if (strSel.Length >= 2)                    // Work with leftmost character
                    {
                        if (char.IsSurrogatePair(strSel, 0))
                        {
                            strChar = strSel.Substring(0, 2);
                        }
                        else
                        {
                            strChar = strSel.Substring(0, 1);
                        }
                    }
                    else if (strSel.Length == 0)                    // Work with char. to the left
                    {
                        int    p       = iSel - 1;
                        string strText = this.Text;
                        if ((p < 0) || (p >= strText.Length))
                        {
                            return(true);
                        }

                        char ch = strText[p];

                        if (!char.IsSurrogate(ch))
                        {
                            strChar = new string(ch, 1);
                        }
                        else if (p >= 1)
                        {
                            if (char.IsSurrogatePair(strText, p - 1))
                            {
                                strChar = strText.Substring(p - 1, 2);
                            }
                        }
                    }
                    else                     // strSel.Length == 1
                    {
                        if (char.IsSurrogate(strSel[0]))
                        {
                            Debug.Assert(false);                             // Half surrogate
                            return(true);
                        }
                    }
                    if (strChar.Length == 0)
                    {
                        Debug.Assert(false); return(true);
                    }

                    int    uc     = char.ConvertToUtf32(strChar, 0);
                    string strRep = Convert.ToString(uc, 16).ToUpperInvariant();

                    if (strSel.Length >= 2)
                    {
                        this.Select(iSel, strChar.Length);
                    }
                    else if (strSel.Length == 0)
                    {
                        this.Select(iSel - strChar.Length, strChar.Length);
                        iSel -= strChar.Length;
                    }
                    this.SelectedText = strRep;
                    this.Select(iSel, strRep.Length);
                }
                else                                // Code -> character
                {
                    const uint ucMax    = 0x10FFFF; // Max. using surrogates
                    const int  ccHexMax = 6;        // See e.g. WordPad

                    string strHex = strSel;
                    if (strSel.Length == 0)
                    {
                        int    p       = iSel - 1;
                        string strText = this.Text;
                        while ((p >= 0) && (p < strText.Length))
                        {
                            char ch = strText[p];
                            if (((ch >= '0') && (ch <= '9')) ||
                                ((ch >= 'a') && (ch <= 'f')) ||
                                ((ch >= 'A') && (ch <= 'F')))
                            {
                                strHex = (new string(ch, 1)) + strHex;
                                if (strHex.Length == ccHexMax)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }

                            --p;
                        }
                    }
                    if ((strHex.Length == 0) || !StrUtil.IsHexString(strHex, true))
                    {
                        return(true);
                    }

                    string strHexTr = strHex.TrimStart('0');
                    if (strHexTr.Length > ccHexMax)
                    {
                        return(true);
                    }

                    uint uc = Convert.ToUInt32(strHexTr, 16);
                    if (uc > ucMax)
                    {
                        return(true);
                    }

                    string strRep = char.ConvertFromUtf32((int)uc);
                    if (string.IsNullOrEmpty(strRep))
                    {
                        Debug.Assert(false); return(true);
                    }
                    if (char.IsControl(strRep, 0) && (strRep[0] != '\t'))
                    {
                        return(true);
                    }

                    if (strSel.Length == 0)
                    {
                        this.Select(iSel - strHex.Length, strHex.Length);
                    }
                    this.SelectedText = strRep;
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(true);
        }
Beispiel #16
0
        internal static bool PerformGlobal(List <PwDatabase> lSources,
                                           ImageList ilIcons, string strSeq)
        {
            if (lSources == null)
            {
                Debug.Assert(false); return(false);
            }

            if (NativeLib.IsUnix())
            {
                if (!NativeMethods.TryXDoTool(true) && !NativeLib.IsWayland())
                {
                    MessageService.ShowWarning(KPRes.AutoTypeXDoToolRequiredGlobalVer);
                    return(false);
                }
            }

            IntPtr hWnd;
            string strWindow;

            GetForegroundWindowInfo(out hWnd, out strWindow);

            // if(string.IsNullOrEmpty(strWindow)) return false;
            if (strWindow == null)
            {
                Debug.Assert(false); return(false);
            }
            if (!IsValidAutoTypeWindow(hWnd, true))
            {
                return(false);
            }

            SequenceQueriesEventArgs evQueries = GetSequencesForWindowBegin(
                hWnd, strWindow);

            List <AutoTypeCtx> lCtxs     = new List <AutoTypeCtx>();
            PwDatabase         pdCurrent = null;
            bool     bExpCanMatch        = Program.Config.Integration.AutoTypeExpiredCanMatch;
            DateTime dtNow = DateTime.UtcNow;

            EntryHandler eh = delegate(PwEntry pe)
            {
                if (!bExpCanMatch && pe.Expires && (pe.ExpiryTime <= dtNow))
                {
                    return(true);                    // Ignore expired entries
                }
                List <string> lSeq = GetSequencesForWindow(pe, hWnd, strWindow,
                                                           pdCurrent, evQueries.EventID);

                if (!string.IsNullOrEmpty(strSeq) && (lSeq.Count != 0))
                {
                    lCtxs.Add(new AutoTypeCtx(strSeq, pe, pdCurrent));
                }
                else
                {
                    foreach (string strSeqCand in lSeq)
                    {
                        lCtxs.Add(new AutoTypeCtx(strSeqCand, pe, pdCurrent));
                    }
                }

                return(true);
            };

            foreach (PwDatabase pd in lSources)
            {
                if ((pd == null) || !pd.IsOpen)
                {
                    continue;
                }
                pdCurrent = pd;
                pd.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh);
            }

            GetSequencesForWindowEnd(evQueries);

            bool bForceDlg = Program.Config.Integration.AutoTypeAlwaysShowSelDialog;

            if ((lCtxs.Count >= 2) || bForceDlg)
            {
                AutoTypeCtxForm dlg = new AutoTypeCtxForm();
                dlg.InitEx(lCtxs, ilIcons);

                bool        bOK = (dlg.ShowDialog() == DialogResult.OK);
                AutoTypeCtx ctx = (bOK ? dlg.SelectedCtx : null);
                UIUtil.DestroyForm(dlg);

                if (ctx != null)
                {
                    try { NativeMethods.EnsureForegroundWindow(hWnd); }
                    catch (Exception) { Debug.Assert(false); }

                    int    nActDelayMS = TargetActivationDelay;
                    string strWindowT  = strWindow.Trim();

                    // https://sourceforge.net/p/keepass/discussion/329220/thread/3681f343/
                    // This apparently is only required here (after showing the
                    // auto-type entry selection dialog), not when using the
                    // context menu command in the main window
                    if (strWindowT.EndsWith("Microsoft Edge", StrUtil.CaseIgnoreCmp))
                    {
                        // 700 skips the first 1-2 characters,
                        // 750 sometimes skips the first character
                        nActDelayMS = 1000;
                    }

                    // Allow target window to handle its activation
                    // (required by some applications, e.g. Edge)
                    Application.DoEvents();
                    Thread.Sleep(nActDelayMS);
                    Application.DoEvents();

                    AutoType.PerformInternal(ctx, strWindow);
                }
            }
            else if (lCtxs.Count == 1)
            {
                AutoType.PerformInternal(lCtxs[0], strWindow);
            }

            return(true);
        }
Beispiel #17
0
        private static void MainPriv(string[] args)
        {
#if DEBUG
            // Program.DesignMode should not be queried before executing
            // Main (e.g. by a static Control) when running the program
            // normally
            Debug.Assert(!m_bDesignModeQueried);
#endif
            m_bDesignMode = false;             // Designer doesn't call Main method

            m_cmdLineArgs = new CommandLineArgs(args);

            // Before loading the configuration
            string strWa = m_cmdLineArgs[AppDefs.CommandLineOptions.WorkaroundDisable];
            if (!string.IsNullOrEmpty(strWa))
            {
                MonoWorkarounds.SetEnabled(strWa, false);
            }
            strWa = m_cmdLineArgs[AppDefs.CommandLineOptions.WorkaroundEnable];
            if (!string.IsNullOrEmpty(strWa))
            {
                MonoWorkarounds.SetEnabled(strWa, true);
            }

            try
            {
                DpiUtil.ConfigureProcess();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.DoEvents();                 // Required
            }
            catch (Exception) { Debug.Assert(MonoWorkarounds.IsRequired(106)); }

#if DEBUG
            string strInitialWorkDir = WinUtil.GetWorkingDirectory();
#endif

            if (!CommonInit())
            {
                CommonTerminate(); return;
            }

            if (m_appConfig.Application.Start.PluginCacheClearOnce)
            {
                PlgxCache.Clear();
                m_appConfig.Application.Start.PluginCacheClearOnce = false;
                AppConfigSerializer.Save(Program.Config);
            }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName2, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null)
            {
                // All important .NET assemblies are in memory now already
                try { SelfTest.Perform(); }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }

            /* if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigAddUrlOverride] != null)
            {
                bool bAct = (m_cmdLineArgs[AppDefs.CommandLineOptions.Activate] != null);
                Program.Config.Integration.UrlSchemeOverrides.AddCustomOverride(
                    m_cmdLineArgs[AppDefs.CommandLineOptions.Scheme],
                    m_cmdLineArgs[AppDefs.CommandLineOptions.Value], bAct, bAct);
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigRemoveUrlOverride] != null)
            {
                Program.Config.Integration.UrlSchemeOverrides.RemoveCustomOverride(
                    m_cmdLineArgs[AppDefs.CommandLineOptions.Scheme],
                    m_cmdLineArgs[AppDefs.CommandLineOptions.Value]);
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null)
            {
                MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString());
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null)
            {
                XmlSerializerEx.GenerateSerializers(m_cmdLineArgs);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXspFile] != null)
            {
                XspArchive.CreateFile(m_cmdLineArgs.FileName, m_cmdLineArgs["d"]);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null)
            {
                Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString);
                Console.WriteLine(PwDefs.Copyright);
                MainCleanUp();
                return;
            }
#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.TestGfx] != null)
            {
                List <Image> lImg = new List <Image>();
                lImg.Add(Properties.Resources.B16x16_Browser);
                lImg.Add(Properties.Resources.B48x48_Keyboard_Layout);
                ImageArchive aHighRes = new ImageArchive();
                aHighRes.Load(Properties.Resources.Images_Client_HighRes);
                lImg.Add(aHighRes.GetForObject("C12_IRKickFlash"));
                if (File.Exists("Test.png"))
                {
                    lImg.Add(Image.FromFile("Test.png"));
                }
                Image img = GfxUtil.ScaleTest(lImg.ToArray());
                img.Save("GfxScaleTest.png", ImageFormat.Png);
                return;
            }
#endif
            // #if (DEBUG && !KeePassLibSD)
            // if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            // {
            //	PopularPasswords.MakeList();
            //	MainCleanUp();
            //	return;
            // }
            // #endif

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Exit);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoType);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypePassword] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoTypePassword);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null)
            {
                string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid];
                if (!string.IsNullOrEmpty(strEntryUuid))
                {
                    IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl,
                                                      strEntryUuid, null, null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipUrl, false);
                }

                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.Cancel] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Cancel);
                return;
            }

            string strIpc  = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent];
            string strIpc1 = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent1];
            if ((strIpc != null) || (strIpc1 != null))
            {
                bool   bIpc1   = (strIpc1 != null);
                string strName = (bIpc1 ? strIpc1 : strIpc);
                if (strName.Length != 0)
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipcP = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName,
                                                     CommandLineArgs.SafeSerialize(vFlt), null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipcP, bIpc1);
                }

                MainCleanUp();
                return;
            }

            // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);
            bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true);
            // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            CustomMessageFilterEx cmfx = new CustomMessageFilterEx();
            Application.AddMessageFilter(cmfx);

#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
            {
                throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
            }

            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
                {
                    throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
                }

                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg) { ShowFatal(exPrg); }
#endif

            Application.RemoveMessageFilter(cmfx);

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

#if DEBUG
            string strEndWorkDir = WinUtil.GetWorkingDirectory();
            Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp));
#endif

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); }
        }
Beispiel #18
0
        static WinUtil()
        {
            OperatingSystem os = Environment.OSVersion;
            Version         v  = os.Version;

            m_bIsWindows9x   = (os.Platform == PlatformID.Win32Windows);
            m_bIsWindows2000 = ((v.Major == 5) && (v.Minor == 0));
            m_bIsWindowsXP   = ((v.Major == 5) && (v.Minor == 1));

            m_bIsAtLeastWindows2000  = (v.Major >= 5);
            m_bIsAtLeastWindowsVista = (v.Major >= 6);
            m_bIsAtLeastWindows7     = ((v.Major >= 7) || ((v.Major == 6) && (v.Minor >= 1)));
            m_bIsAtLeastWindows8     = ((v.Major >= 7) || ((v.Major == 6) && (v.Minor >= 2)));

            // Environment.OSVersion is reliable only up to version 6.2;
            // https://msdn.microsoft.com/library/windows/desktop/ms724832.aspx
            RegistryKey rk = null;

            try
            {
                rk = Registry.LocalMachine.OpenSubKey(
                    "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", false);
                if (rk != null)
                {
                    string str = rk.GetValue("CurrentMajorVersionNumber",
                                             string.Empty).ToString();
                    uint u;
                    if (uint.TryParse(str, out u))
                    {
                        m_bIsAtLeastWindows10 = (u >= 10);
                    }
                    else
                    {
                        Debug.Assert(string.IsNullOrEmpty(str));
                    }
                }
                else
                {
                    Debug.Assert(NativeLib.IsUnix());
                }
            }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }
            finally { if (rk != null)
                      {
                          rk.Close();
                      }
            }

            try
            {
                string strDir = UrlUtil.GetFileDirectory(GetExecutable(), false, false);
                if (strDir.IndexOf("\\WindowsApps\\", StrUtil.CaseIgnoreCmp) >= 0)
                {
                    Regex rx = new Regex("\\\\WindowsApps\\\\.*?_\\d+(\\.\\d+)*_",
                                         RegexOptions.IgnoreCase);
                    m_bIsAppX = rx.IsMatch(strDir);
                }
                else
                {
                    Debug.Assert(!m_bIsAppX);
                }                                                  // No AppX by default
            }
            catch (Exception) { Debug.Assert(false); }
        }
Beispiel #19
0
        public static void SendKeysWait(string strKeys, bool bObfuscate)
        {
            if (strKeys == null)
            {
                Debug.Assert(false); return;
            }

            List <SiEvent> l = Parse(strKeys);

            if (l.Count == 0)
            {
                return;
            }

            if (bObfuscate)
            {
                SiObf.Obfuscate(l);
            }

            FixEventSeq(l);

            ISiEngine si = null;

            if (SendInputEx.CreateEngine != null)
            {
                SiEventArgs ea = new SiEventArgs();
                SendInputEx.CreateEngine(null, ea);
                si = ea.Engine;
            }
            if (si == null)
            {
                if (NativeLib.IsUnix())
                {
                    si = new SiEngineUnix();
                }
                else
                {
                    si = new SiEngineWin();
                }
            }

            bool bInter = Program.Config.Integration.AutoTypeAllowInterleaved;

            if (!bInter)
            {
                if (!g_csSending.TryEnter())
                {
                    return;
                }
            }

            Interlocked.Increment(ref g_cCurSending);
            try
            {
                si.Init();
                Send(si, l);
            }
            finally
            {
                try { si.Release(); }
                catch (Exception) { Debug.Assert(false); }

                Interlocked.Decrement(ref g_cCurSending);

                if (!bInter)
                {
                    g_csSending.Exit();
                }
            }
        }
        private static void ExecuteShellCmd(EcasAction a, EcasContext ctx)
        {
            string strCmd       = EcasUtil.GetParamString(a.Parameters, 0);
            string strArgs      = EcasUtil.GetParamString(a.Parameters, 1, true, true);
            bool   bWait        = EcasUtil.GetParamBool(a.Parameters, 2);
            uint   uWindowStyle = EcasUtil.GetParamUInt(a.Parameters, 3);
            string strVerb      = EcasUtil.GetParamString(a.Parameters, 4, true);

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

            Process p = null;

            try
            {
                PwEntry pe = null;
                try { pe = Program.MainForm.GetSelectedEntry(false); }
                catch (Exception) { Debug.Assert(false); }

                strCmd = WinUtil.CompileUrl(strCmd, pe, true, null, false);

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = NativeLib.EncodePath(strCmd);
                if (!string.IsNullOrEmpty(strArgs))
                {
                    psi.Arguments = strArgs;
                }

                bool bShEx = true;
                if (!string.IsNullOrEmpty(strVerb))
                {
                }                                                      // Need ShellExecute
                else if ((uWindowStyle == IdWindowMin) ||
                         (uWindowStyle == IdWindowMax))
                {
                }                                                          // Need ShellExecute
                else
                {
                    string strCmdFlt = strCmd.TrimEnd(new char[] { '\"', '\'',
                                                                   ' ', '\t', '\r', '\n' });
                    if (strCmdFlt.EndsWith(".exe", StrUtil.CaseIgnoreCmp) ||
                        strCmdFlt.EndsWith(".com", StrUtil.CaseIgnoreCmp))
                    {
                        bShEx = false;
                    }
                }
                psi.UseShellExecute = bShEx;

                if (uWindowStyle == IdWindowHidden)
                {
                    psi.CreateNoWindow = true;
                    psi.WindowStyle    = ProcessWindowStyle.Hidden;
                }
                else if (uWindowStyle == IdWindowMin)
                {
                    psi.WindowStyle = ProcessWindowStyle.Minimized;
                }
                else if (uWindowStyle == IdWindowMax)
                {
                    psi.WindowStyle = ProcessWindowStyle.Maximized;
                }

                if (!string.IsNullOrEmpty(strVerb))
                {
                    psi.Verb = strVerb;
                }

                p = Process.Start(psi);

                if ((p != null) && bWait)
                {
                    Program.MainForm.UIBlockInteraction(true);
                    MessageService.ExternalIncrementMessageCount();

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

                    MessageService.ExternalDecrementMessageCount();
                    Program.MainForm.UIBlockInteraction(false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(strCmd + MessageService.NewParagraph + ex.Message);
            }
            finally
            {
                try { if (p != null)
                      {
                          p.Dispose();
                      }
                }
                catch (Exception) { Debug.Assert(false); }
            }
        }
Beispiel #21
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            Debug.Assert(m_atConfig != null); if (m_atConfig == null)
            {
                throw new InvalidOperationException();
            }
            Debug.Assert(m_vStringDict != null); if (m_vStringDict == null)
            {
                throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this);

            m_ctxKeySeq.Attach(m_rbKeySeq, this);
            m_ctxKeyCodes.Attach(m_rtbPlaceholders, this);

            if (!m_bEditSequenceOnly)
            {
                BannerFactory.CreateBannerEx(this, m_bannerImage,
                                             Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureAutoTypeItem,
                                             KPRes.ConfigureAutoTypeItemDesc);
            }
            else             // Edit keystrokes only
            {
                BannerFactory.CreateBannerEx(this, m_bannerImage,
                                             Properties.Resources.B48x48_KCMSystem, KPRes.ConfigureKeystrokeSeq,
                                             KPRes.ConfigureKeystrokeSeqDesc);
            }

            this.Icon = AppIcons.Default;

            // FontUtil.AssignDefaultBold(m_lblTargetWindow);
            // FontUtil.AssignDefaultBold(m_rbSeqDefault);
            // FontUtil.AssignDefaultBold(m_rbSeqCustom);

            UIUtil.EnableAutoCompletion(m_cmbWindow, false);

            // m_clrOriginalForeground = m_lblOpenHint.ForeColor;
            // m_clrOriginalBackground = m_cmbWindow.BackColor;
            // m_strOriginalWindowHint = m_lblTargetWindowInfo.Text;

            bool bRtl = Program.Translation.Properties.RightToLeft;

            if (bRtl)
            {
                // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
                m_rbKeySeq.RightToLeft        = RightToLeft.No;
                m_rtbPlaceholders.RightToLeft = RightToLeft.No;
            }

            InitPlaceholdersBox(bRtl);

            string strInitSeq = m_atConfig.DefaultSequence;

            if (m_iAssocIndex >= 0)
            {
                AutoTypeAssociation asInit = m_atConfig.GetAt(m_iAssocIndex);
                m_cmbWindow.Text = asInit.WindowName;

                if (!m_bEditSequenceOnly)
                {
                    strInitSeq = asInit.Sequence;
                }
            }
            else if (m_bEditSequenceOnly)
            {
                m_cmbWindow.Text = "(" + KPRes.Default + ")";
            }
            else
            {
                strInitSeq = string.Empty;
            }

            bool bSetDefault = false;

            m_bBlockUpdates = true;
            if (strInitSeq.Length > 0)
            {
                m_rbSeqCustom.Checked = true;
            }
            else
            {
                m_rbSeqDefault.Checked = true;
                bSetDefault            = true;
            }
            m_bBlockUpdates = false;

            if (bSetDefault)
            {
                m_rbKeySeq.Text = m_strDefaultSeq;
            }
            else
            {
                m_rbKeySeq.Text = strInitSeq;
            }

            try
            {
                if (NativeLib.IsUnix())
                {
                    PopulateWindowsListUnix();
                }
                else
                {
                    PopulateWindowsListWin();
                }
            }
            catch (Exception) { Debug.Assert(false); }

            EnableControlsEx();
        }
Beispiel #22
0
        public static void ConfigureProcess()
        {
            if (NativeLib.IsUnix())
            {
                return;
            }

            // try
            // {
            //	ConfigurationManager.AppSettings.Set(
            //		"EnableWindowsFormsHighDpiAutoResizing", "true");
            // }
            // catch(Exception) { Debug.Assert(false); }
#if DEBUG
            // Ensure that the .config file enables high DPI features
            string strExeConfig = WinUtil.GetExecutable() + ".config";
            if (File.Exists(strExeConfig))
            {
                string strCM = "System.Configuration.ConfigurationManager, ";
                strCM += "System.Configuration, Version=";
                strCM += Environment.Version.Major.ToString() + ".0.0.0, ";
                strCM += "Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

                Type tCM = Type.GetType(strCM, false);
                if (tCM != null)
                {
                    PropertyInfo pi = tCM.GetProperty("AppSettings",
                                                      (BindingFlags.Public | BindingFlags.Static));
                    if (pi != null)
                    {
                        NameValueCollection nvc = (pi.GetValue(null, null) as
                                                   NameValueCollection);
                        if (nvc != null)
                        {
                            Debug.Assert(string.Equals(nvc.Get(
                                                           "EnableWindowsFormsHighDpiAutoResizing"),
                                                       "true", StrUtil.CaseIgnoreCmp));
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    Debug.Assert(false);
                }                                             // Assembly should be loaded
            }
#endif

            try
            {
                // SetProcessDPIAware is obsolete; use
                // SetProcessDpiAwareness on Windows 10 and higher
                if (WinUtil.IsAtLeastWindows10)                // 8.1 partially
                {
                    if (NativeMethods.SetProcessDpiAwareness(
                            NativeMethods.ProcessDpiAwareness.SystemAware) < 0)
                    {
                        Debug.Assert(false);
                    }
                }
                else if (WinUtil.IsAtLeastWindowsVista)
                {
                    if (!NativeMethods.SetProcessDPIAware())
                    {
                        Debug.Assert(false);
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Beispiel #23
0
        public static byte[] ComputeHash()
        {
            try             // This works always or never
            {
                bool bOpened = OpenW(IntPtr.Zero, false);
                // The following seems to work even without opening the
                // clipboard, but opening maybe is safer
                uint u = NativeMethods.GetClipboardSequenceNumber();
                if (bOpened)
                {
                    CloseW();
                }

                if (u == 0)
                {
                    throw new UnauthorizedAccessException();
                }

                return(CryptoUtil.HashSha256(MemUtil.UInt32ToBytes(u)));
            }
            catch (Exception) { Debug.Assert(false); }

            if (NativeLib.GetPlatformID() == PlatformID.MacOSX)
            {
                string str    = GetStringM();
                byte[] pbText = StrUtil.Utf8.GetBytes("pb" + str);
                return(CryptoUtil.HashSha256(pbText));
            }
            if (NativeLib.IsUnix())
            {
                string str    = GetStringU();
                byte[] pbText = StrUtil.Utf8.GetBytes("pb" + str);
                return(CryptoUtil.HashSha256(pbText));
            }

            try
            {
                MemoryStream ms = new MemoryStream();

                byte[] pbPre = StrUtil.Utf8.GetBytes("pb");
                ms.Write(pbPre, 0, pbPre.Length);                 // Prevent empty buffer

                if (Clipboard.ContainsAudio())
                {
                    Stream sAudio = Clipboard.GetAudioStream();
                    MemUtil.CopyStream(sAudio, ms);
                    sAudio.Close();
                }

                if (Clipboard.ContainsFileDropList())
                {
                    StringCollection sc = Clipboard.GetFileDropList();
                    foreach (string str in sc)
                    {
                        byte[] pbStr = StrUtil.Utf8.GetBytes(str);
                        ms.Write(pbStr, 0, pbStr.Length);
                    }
                }

                if (Clipboard.ContainsImage())
                {
                    using (Image img = Clipboard.GetImage())
                    {
                        MemoryStream msImage = new MemoryStream();
                        img.Save(msImage, ImageFormat.Bmp);
                        byte[] pbImg = msImage.ToArray();
                        ms.Write(pbImg, 0, pbImg.Length);
                        msImage.Close();
                    }
                }

                if (Clipboard.ContainsText())
                {
                    string str    = Clipboard.GetText();
                    byte[] pbText = StrUtil.Utf8.GetBytes(str);
                    ms.Write(pbText, 0, pbText.Length);
                }

                byte[] pbData = ms.ToArray();
                byte[] pbHash = CryptoUtil.HashSha256(pbData);
                ms.Close();

                return(pbHash);
            }
            catch (Exception) { Debug.Assert(false); }

            return(null);
        }
Beispiel #24
0
        public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo,
                                PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner)
        {
            if (strToCopy == null)
            {
                throw new ArgumentNullException("strToCopy");
            }
            if (strToCopy.Length == 0)
            {
                Clear(); return(true);
            }

            if (bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
            {
                return(false);
            }

            string strData = strToCopy;

            if (bSprCompile)
            {
                strData = SprEngine.Compile(strData, new SprContext(
                                                peEntryInfo, pwReferenceSource, SprCompileFlags.All));
            }

            try
            {
                // if(SetStringUwp(strData)) { } else
                if (!NativeLib.IsUnix())                // Windows
                {
                    if (!OpenW(hOwner, true))
                    {
                        throw new InvalidOperationException();
                    }

                    bool bFailed = false;
                    if (!AttachIgnoreFormatsW())
                    {
                        bFailed = true;
                    }
                    if (!SetDataW(null, strData, null))
                    {
                        bFailed = true;
                    }
                    CloseW();

                    if (bFailed)
                    {
                        return(false);
                    }
                }
                else if (NativeLib.GetPlatformID() == PlatformID.MacOSX)
                {
                    SetStringM(strData);
                }
                else if (NativeLib.IsUnix())
                {
                    SetStringU(strData);
                }
                else
                {
                    Debug.Assert(false);
                    Clipboard.SetText(strData);
                }
            }
            catch (Exception) { Debug.Assert(false); return(false); }

            g_pbDataHash = HashString(strData);

            if (peEntryInfo != null)
            {
                peEntryInfo.Touch(false);
            }

            if (bIsEntryInfo)
            {
                Program.TriggerSystem.RaiseEvent(EcasEventIDs.CopiedEntryInfo,
                                                 EcasProperty.Text, strData);
            }

            // SprEngine.Compile might have modified the database
            MainForm mf = Program.MainForm;

            if ((mf != null) && bSprCompile)
            {
                mf.RefreshEntriesList();
                mf.UpdateUI(false, null, false, null, false, null, false);
            }

            return(true);
        }