Ejemplo n.º 1
0
        internal string GetTotpSettings(PwEntry entry)
        {
            PwEntryDatabase entryDatabase = new PwEntryDatabase(entry, HostInstance.Database);
            SprContext      ctx           = new SprContext(entryDatabase.entry, entryDatabase.database,
                                                           SprCompileFlags.All, false, false);

            string settings = SprEngine.Compile(entryDatabase.entry.Strings.ReadSafe("otp"), ctx);
            var    f        = (MethodInvoker) delegate
            {
                // apparently, SprEngine.Compile might modify the database
                HostInstance.MainWindow.UpdateUI(false, null, false, null, false, null, false);
            };

            if (HostInstance.MainWindow.InvokeRequired)
            {
                HostInstance.MainWindow.Invoke(f);
            }
            else
            {
                f.Invoke();
            }

            return(settings);
        }
Ejemplo n.º 2
0
        private static string GeneratePassword(string strProfile, SprContext ctx)
        {
            PwProfile prf = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile;

            if (!string.IsNullOrEmpty(strProfile))
            {
                if (strProfile == @"~")
                {
                    prf = PwProfile.DeriveFromPassword(ctx.Entry.Strings.GetSafe(
                                                           PwDefs.PasswordField));
                }
                else
                {
                    List <PwProfile> lPrf = PwGeneratorUtil.GetAllProfiles(false);
                    foreach (PwProfile p in lPrf)
                    {
                        if (strProfile.Equals(p.Name, StrUtil.CaseIgnoreCmp))
                        {
                            prf = p;
                            break;
                        }
                    }
                }
            }

            ProtectedString ps;
            PwgError        e = PwGenerator.Generate(out ps, prf, null,
                                                     Program.PwGeneratorPool);

            if ((e != PwgError.Success) || (ps == null))
            {
                return(string.Empty);
            }

            return(ps.ReadString());
        }
Ejemplo n.º 3
0
        internal string[] GetUserPass(PwEntryDatabase entryDatabase, SprContext ctx)
        {
            // follow references
            string user = SprEngine.Compile(
                entryDatabase.entry.Strings.ReadSafe(PwDefs.UserNameField), ctx);
            string pass = SprEngine.Compile(
                entryDatabase.entry.Strings.ReadSafe(PwDefs.PasswordField), ctx);
            var f = (MethodInvoker) delegate
            {
                // apparently, SprEngine.Compile might modify the database
                HostInstance.MainWindow.UpdateUI(false, null, false, null, false, null, false);
            };

            if (HostInstance.MainWindow.InvokeRequired)
            {
                HostInstance.MainWindow.Invoke(f);
            }
            else
            {
                f.Invoke();
            }

            return(new string[] { user, pass });
        }
Ejemplo n.º 4
0
        private void UpdateUI()
        {
            if ((m_uBlockUIUpdate > 0) || m_bInitializing)
            {
                return;
            }
            ++m_uBlockUIUpdate;

            ulong uFlags = 0;

            if (m_fParent is KeyCreationForm)
            {
                uFlags = Program.Config.UI.KeyCreationFlags;
            }

            byte[] pbUtf8 = m_secPassword.ToUtf8();
            string str    = StrUtil.Utf8.GetString(pbUtf8);

#if DEBUG
            byte[] pbTest = StrUtil.Utf8.GetBytes(str);
            Debug.Assert(MemUtil.ArraysEqual(pbUtf8, pbTest));
#endif

            m_tbPassword.Enabled = m_bEnabled;
            m_cbHide.Enabled     = (m_bEnabled && ((uFlags &
                                                    (ulong)AceKeyUIFlags.DisableHidePassword) == 0));

            if ((uFlags & (ulong)AceKeyUIFlags.CheckHidePassword) != 0)
            {
                ++m_uPrgmCheck;
                m_cbHide.Checked = true;
                --m_uPrgmCheck;
            }
            if ((uFlags & (ulong)AceKeyUIFlags.UncheckHidePassword) != 0)
            {
                ++m_uPrgmCheck;
                m_cbHide.Checked = false;
                --m_uPrgmCheck;
            }

            bool bAutoRepeat = this.AutoRepeat;
            if (bAutoRepeat && (m_secRepeat.TextLength > 0))
            {
                m_secRepeat.SetPassword(MemUtil.EmptyByteArray);
            }

            byte[] pbRepeat = m_secRepeat.ToUtf8();
            if (!MemUtil.ArraysEqual(pbUtf8, pbRepeat) && !bAutoRepeat)
            {
                m_tbRepeat.BackColor = AppDefs.ColorEditError;
            }
            else
            {
                m_tbRepeat.ResetBackColor();
            }

            bool bRepeatEnable = (m_bEnabled && !bAutoRepeat);
            m_lblRepeat.Enabled = bRepeatEnable;
            m_tbRepeat.Enabled  = bRepeatEnable;

            bool bQuality = m_bEnabled;
            if (m_bSprVar && bQuality)
            {
                if (SprEngine.MightChange(str))                // Perf. opt.
                {
                    // {S:...} and {REF:...} may reference the entry that
                    // is currently being edited and SprEngine will not see
                    // the current data entered in the dialog; thus we
                    // disable quality estimation for all strings containing
                    // one of these placeholders
                    if ((str.IndexOf(@"{S:", StrUtil.CaseIgnoreCmp) >= 0) ||
                        (str.IndexOf(@"{REF:", StrUtil.CaseIgnoreCmp) >= 0))
                    {
                        bQuality = false;
                    }
                    else
                    {
                        SprContext ctx = new SprContext(m_ctxEntry, m_ctxDatabase,
                                                        SprCompileFlags.NonActive, false, false);
                        string strCmp = SprEngine.Compile(str, ctx);
                        if (strCmp != str)
                        {
                            bQuality = false;
                        }
                    }
                }
#if DEBUG
                else
                {
                    SprContext ctx = new SprContext(m_ctxEntry, m_ctxDatabase,
                                                    SprCompileFlags.NonActive, false, false);
                    string strCmp = SprEngine.Compile(str, ctx);
                    Debug.Assert(strCmp == str);
                }
#endif
            }

            m_lblQualityPrompt.Enabled = bQuality;
            m_pbQuality.Enabled        = bQuality;
            m_lblQualityInfo.Enabled   = bQuality;

            if ((Program.Config.UI.UIFlags & (ulong)AceUIFlags.HidePwQuality) != 0)
            {
                m_lblQualityPrompt.Visible = false;
                m_pbQuality.Visible        = false;
                m_lblQualityInfo.Visible   = false;
            }
            else if (bQuality || !m_bSprVar)
            {
                UpdateQualityInfo(str);
            }
            else
            {
                UqiShowQuality(0, 0);
            }

            // MemUtil.ZeroByteArray(pbUtf8);
            // MemUtil.ZeroByteArray(pbRepeat);
            --m_uBlockUIUpdate;
        }
Ejemplo n.º 5
0
        public static void OpenUrl(string strUrlToOpen, PwEntry peDataSource,
                                   bool bAllowOverride, string strBaseRaw)
        {
            // If URL is null, return, do not throw exception.
            Debug.Assert(strUrlToOpen != null); if (strUrlToOpen == null)
            {
                return;
            }

            string strPrevWorkDir = WinUtil.GetWorkingDirectory();
            string strThisExe     = WinUtil.GetExecutable();

            string strExeDir = UrlUtil.GetFileDirectory(strThisExe, false, true);

            WinUtil.SetWorkingDirectory(strExeDir);

            string strUrlFlt = strUrlToOpen;

            strUrlFlt = strUrlFlt.TrimStart(new char[] { ' ', '\t', '\r', '\n' });

            PwDatabase pwDatabase = null;

            try
            {
                pwDatabase = Program.MainForm.DocumentManager.SafeFindContainerOf(
                    peDataSource);
            }
            catch (Exception) { Debug.Assert(false); }

            bool bCmdQuotes = WinUtil.IsCommandLineUrl(strUrlFlt);

            SprContext ctx = new SprContext(peDataSource, pwDatabase,
                                            SprCompileFlags.All, false, bCmdQuotes);

            ctx.Base          = strBaseRaw;
            ctx.BaseIsEncoded = false;

            string strUrl = SprEngine.Compile(strUrlFlt, ctx);

            string strOvr = Program.Config.Integration.UrlSchemeOverrides.GetOverrideForUrl(
                strUrl);

            if (!bAllowOverride)
            {
                strOvr = null;
            }
            if (strOvr != null)
            {
                bool bCmdQuotesOvr = WinUtil.IsCommandLineUrl(strOvr);

                SprContext ctxOvr = new SprContext(peDataSource, pwDatabase,
                                                   SprCompileFlags.All, false, bCmdQuotesOvr);
                ctxOvr.Base          = strUrl;
                ctxOvr.BaseIsEncoded = bCmdQuotes;

                strUrl = SprEngine.Compile(strOvr, ctxOvr);
            }

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                string strApp, strArgs;
                StrUtil.SplitCommandLine(WinUtil.GetCommandLineFromUrl(strUrl),
                                         out strApp, out strArgs);

                try
                {
                    if ((strArgs != null) && (strArgs.Length > 0))
                    {
                        Process.Start(strApp, strArgs);
                    }
                    else
                    {
                        Process.Start(strApp);
                    }
                }
                catch (Win32Exception)
                {
                    StartWithoutShellExecute(strApp, strArgs);
                }
                catch (Exception exCmd)
                {
                    string strInf = KPRes.FileOrUrl + ": " + strApp;
                    if ((strArgs != null) && (strArgs.Length > 0))
                    {
                        strInf += MessageService.NewParagraph +
                                  KPRes.Arguments + ": " + strArgs;
                    }

                    MessageService.ShowWarning(strInf, exCmd);
                }
            }
            else             // Standard URL
            {
                try { Process.Start(strUrl); }
                catch (Exception exUrl)
                {
                    MessageService.ShowWarning(strUrl, exUrl);
                }
            }

            // Restore previous working directory
            WinUtil.SetWorkingDirectory(strPrevWorkDir);

            // SprEngine.Compile might have modified the database
            Program.MainForm.UpdateUI(false, null, false, null, false, null, false);
        }
Ejemplo n.º 6
0
 public static string FillPlaceholders(string strText, SprContext ctx)
 {
     return(FillPlaceholders(strText, ctx, 0));
 }
Ejemplo n.º 7
0
        private static string ReplaceHmacOtpPlaceholder(string strText,
                                                        SprContext ctx)
        {
            PwEntry    pe = ctx.Entry;
            PwDatabase pd = ctx.Database;

            if ((pe == null) || (pd == null))
            {
                return(strText);
            }

            string str = strText;

            const string strHmacOtpPlh = @"{HMACOTP}";

            if (str.IndexOf(strHmacOtpPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                const string strKeyFieldUtf8   = "HmacOtp-Secret";
                const string strKeyFieldHex    = "HmacOtp-Secret-Hex";
                const string strKeyFieldBase32 = "HmacOtp-Secret-Base32";
                const string strKeyFieldBase64 = "HmacOtp-Secret-Base64";
                const string strCounterField   = "HmacOtp-Counter";

                byte[] pbSecret = null;
                try
                {
                    string strKey = pe.Strings.ReadSafe(strKeyFieldUtf8);
                    if (strKey.Length > 0)
                    {
                        pbSecret = StrUtil.Utf8.GetBytes(strKey);
                    }

                    if (pbSecret == null)
                    {
                        strKey = pe.Strings.ReadSafe(strKeyFieldHex);
                        if (strKey.Length > 0)
                        {
                            pbSecret = MemUtil.HexStringToByteArray(strKey);
                        }
                    }

                    if (pbSecret == null)
                    {
                        strKey = pe.Strings.ReadSafe(strKeyFieldBase32);
                        if (strKey.Length > 0)
                        {
                            pbSecret = MemUtil.ParseBase32(strKey);
                        }
                    }

                    if (pbSecret == null)
                    {
                        strKey = pe.Strings.ReadSafe(strKeyFieldBase64);
                        if (strKey.Length > 0)
                        {
                            pbSecret = Convert.FromBase64String(strKey);
                        }
                    }
                }
                catch (Exception) { Debug.Assert(false); }
                if (pbSecret == null)
                {
                    pbSecret = new byte[0];
                }

                string strCounter = pe.Strings.ReadSafe(strCounterField);
                ulong  uCounter;
                ulong.TryParse(strCounter, out uCounter);

                string strValue = HmacOtp.Generate(pbSecret, uCounter, 6,
                                                   false, -1);

                pe.Strings.Set(strCounterField, new ProtectedString(false,
                                                                    (uCounter + 1).ToString()));
                pd.Modified = true;

                str = StrUtil.ReplaceCaseInsensitive(str, strHmacOtpPlh, strValue);
            }

            return(str);
        }
        public string ProcessReplacementTags(ProtectedString protectedString)
        {
            SprContext context = new SprContext(this.entry, this.database, SprCompileFlags.All);

            return(SprEngine.Compile(protectedString.ReadString(), context));
        }
Ejemplo n.º 9
0
        private static List <List <PwEntry> > FindDuplicatePasswordsEx(PwDatabase pd,
                                                                       IStatusLogger sl)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return(null);
            }
            PwGroup pg = pd.RootGroup;

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

            uint uEntries     = pg.GetEntriesCount(true);
            uint uEntriesDone = 0;
            Dictionary <string, List <PwEntry> > d =
                new Dictionary <string, List <PwEntry> >();

            EntryHandler eh = delegate(PwEntry pe)
            {
                if ((sl != null) && (uEntries != 0))
                {
                    uint u = (uEntriesDone * 100) / uEntries;
                    if (!sl.SetProgress(u))
                    {
                        return(false);
                    }

                    ++uEntriesDone;
                }

                if (!pe.GetSearchingEnabled())
                {
                    return(true);
                }

                SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive);
                string     str = SprEngine.Compile(pe.Strings.ReadSafe(
                                                       PwDefs.PasswordField), ctx);
                if (str.Length != 0)
                {
                    List <PwEntry> l;
                    if (d.TryGetValue(str, out l))
                    {
                        l.Add(pe);
                    }
                    else
                    {
                        l = new List <PwEntry>();
                        l.Add(pe);
                        d[str] = l;
                    }
                }

                return(true);
            };

            if (!pg.TraverseTree(TraversalMethod.PreOrder, null, eh))
            {
                return(null);
            }

            List <List <PwEntry> > lRes = new List <List <PwEntry> >();

            foreach (List <PwEntry> l in d.Values)
            {
                if (l.Count <= 1)
                {
                    continue;
                }
                lRes.Add(l);
            }
            lRes.Sort(EntryUtil.CompareListSizeDesc);

            return(lRes);
        }
Ejemplo n.º 10
0
        public static string Compile(string strText, SprContext ctx)
        {
            if(strText == null) { Debug.Assert(false); return string.Empty; }
            if(strText.Length == 0) return string.Empty;

            SprEngine.InitializeStatic();

            if(ctx == null) ctx = new SprContext();
            ctx.RefsCache.Clear();

            string str = SprEngine.CompileInternal(strText, ctx, 0);

            // if(bEscapeForAutoType && !bIsAutoTypeSequence)
            //	str = SprEncoding.MakeAutoTypeSequence(str);

            return str;
        }
Ejemplo n.º 11
0
        private static string FillRefsUsingCache(string strText, SprContext ctx)
        {
            string str = strText;

            foreach(KeyValuePair<string, string> kvp in ctx.RefsCache)
            {
                // str = str.Replace(kvp.Key, kvp.Value);
                str = StrUtil.ReplaceCaseInsensitive(str, kvp.Key, kvp.Value);
            }

            return str;
        }
Ejemplo n.º 12
0
        internal static ProtectedString GenerateAcceptable(PwProfile prf,
                                                           byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx,
                                                           bool bShowErrorUI, ref bool bAcceptAlways, out string strError)
        {
            strError = null;

            ProtectedString ps  = ProtectedString.Empty;
            SprContext      ctx = new SprContext(peOptCtx, pdOptCtx,
                                                 SprCompileFlags.NonActive, false, false);

            while (true)
            {
                try
                {
                    PwgError e = PwGenerator.Generate(out ps, prf, pbUserEntropy,
                                                      Program.PwGeneratorPool);

                    if (e != PwgError.Success)
                    {
                        strError = PwGenerator.ErrorToString(e, true);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    strError = PwGenerator.ErrorToString(ex, true);
                    break;
                }
                finally
                {
                    if (ps == null)
                    {
                        Debug.Assert(false); ps = ProtectedString.Empty;
                    }
                }

                if (bAcceptAlways)
                {
                    break;
                }

                string str    = ps.ReadString();
                string strCmp = SprEngine.Compile(str, ctx);

                if (str != strCmp)
                {
                    if (prf.GeneratorType == PasswordGeneratorType.CharSet)
                    {
                        continue;                         // Silently try again
                    }
                    string strText = str + MessageService.NewParagraph +
                                     KPRes.GenPwSprVariant + MessageService.NewParagraph +
                                     KPRes.GenPwAccept;

                    if (!MessageService.AskYesNo(strText, null, false))
                    {
                        continue;
                    }
                    bAcceptAlways = true;
                }

                break;
            }

            if (!string.IsNullOrEmpty(strError))
            {
                ps = ProtectedString.Empty;
                if (bShowErrorUI)
                {
                    MessageService.ShowWarning(strError);
                }
            }

            return(ps);
        }
Ejemplo n.º 13
0
        public static string Compile(string strText, bool bIsAutoTypeSequence,
			PwEntry pwEntry, PwDatabase pwDatabase, bool bEscapeForAutoType,
			bool bEscapeQuotesForCommandLine)
        {
            SprContext ctx = new SprContext(pwEntry, pwDatabase, SprCompileFlags.All,
                bEscapeForAutoType, bEscapeQuotesForCommandLine);
            return Compile(strText, ctx);
        }
 public static string Compile(string value, SprContext sprContext)
 {
     return(value);
 }
Ejemplo n.º 15
0
        private void GetPasswordStatus()
        {
            var pwd_sha_str = String.Empty;

            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                var context  = new SprContext(PasswordEntry, Host.Database, SprCompileFlags.All);
                var password = SprEngine.Compile(PasswordEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString(), context);

                var pwd_sha_bytes = sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(password));
                var sb            = new StringBuilder(2 * pwd_sha_bytes.Length);

                foreach (byte b in pwd_sha_bytes)
                {
                    sb.AppendFormat("{0:X2}", b);
                }
                pwd_sha_str = sb.ToString();
            }

            var latestFile = PluginOptions.HIBPFileName;

            if (!File.Exists(latestFile))
            {
                Status = "HIBP file not found";
                return;
            }

            using (FileStream fs = File.OpenRead(latestFile))
                using (StreamReader sr = new StreamReader(fs))
                {
                    try
                    {
                        string line;
                        Status = PluginOptions.SecureText;
                        int sha_len = pwd_sha_str.Length;

                        var low  = 0L;
                        var high = fs.Length;

                        while (low <= high)
                        {
                            var middle = (low + high + 1) / 2;
                            fs.Seek(middle, SeekOrigin.Begin);

                            // Resync with base stream after seek
                            sr.DiscardBufferedData();

                            line = sr.ReadLine();

                            if (sr.EndOfStream)
                            {
                                break;
                            }

                            // We may have read only a partial line so read again to make sure we get a full line
                            if (middle > 0)
                            {
                                line = sr.ReadLine() ?? String.Empty;
                            }

                            int compare = String.Compare(pwd_sha_str, line.Substring(0, sha_len), StringComparison.Ordinal);

                            if (compare < 0)
                            {
                                high = middle - 1;
                            }
                            else if (compare > 0)
                            {
                                low = middle + 1;
                            }
                            else
                            {
                                string[] tokens = line.Split(':');
                                Status          = PluginOptions.InsecureText;
                                insecureWarning = true;

                                if (PluginOptions.BreachCountDetails)
                                {
                                    Status += " (password count: " + tokens[1].Trim() + ")";
                                }

                                break;
                            }
                        }
                    }
                    catch
                    {
                        Status = "Failed to read HIBP file";
                    }
                }
        }
Ejemplo n.º 16
0
 public static string Compile(string value, SprContext sprContext)
 {
     return value;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Uses the KeePass SprEngine to resolve field references.
        /// </summary>
        /// <param name="pe"></param>
        /// <param name="pd"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static string ResolveReferences(PwEntry pe, PwDatabase pd, string field)
        {
            var ctx = new SprContext(pe, pd, SprCompileFlags.All);

            return(SprEngine.Compile(pe.Strings.ReadSafe(field), ctx));
        }
Ejemplo n.º 18
0
        public void OnShowQRCode(object sender, DynamicMenuEventArgs e)
        {
            var key = e.Tag as string;

            if (key == null)
            {
                return;
            }

            var pe = host.MainWindow.GetSelectedEntry(true);

            if (pe == null)
            {
                return;
            }

            var context = new SprContext(pe, host.Database, SprCompileFlags.All);
            var value   = SprEngine.Compile(pe.Strings.GetSafe(key).ReadString(), context);

            if (key == "otp" && value.StartsWith("key="))
            {
                var title = SprEngine.Compile(pe.Strings.GetSafe("Title").ReadString(), context);
                var user  = SprEngine.Compile(pe.Strings.GetSafe("UserName").ReadString(), context);

                string label = null;
                if (title == string.Empty && user == string.Empty)
                {
                    label = "Unknown"; //edge case when entry has no title or user, nobody would use KeePass like this but just to be bulletproof
                }
                else if (title == string.Empty || user == string.Empty)
                {
                    label = title + user;
                }
                else
                {
                    label = title + " (" + user + ")"; //Not RFC 5234, but more readable in the auth app
                }

                label = Uri.EscapeDataString(label);
                value = string.Format("otpauth://totp/{0}?secret={1}", label, value.Replace("key=", ""));
            }

            try
            {
                var data = new QRCodeGenerator().CreateQrCode(value, QRCodeGenerator.ECCLevel.L);
                if (data != null)
                {
                    var form = new ShowQRCodeForm(
                        host,
                        data.GetBitmap(10, Color.Black, Color.White),
                        SprEngine.Compile(pe.Strings.GetSafe(PwDefs.TitleField).ReadString(), context),
                        TryTranslateKey(key)
                        );
                    form.ShowDialog();
                }
            }
            catch
            {
                MessageBox.Show("The data can't be displayed as a QR Code.");
            }
        }
Ejemplo n.º 19
0
        private static string FillRefPlaceholders(string strSeq, SprContext ctx,
			uint uRecursionLevel)
        {
            if(ctx.Database == null) return strSeq;

            string str = strSeq;

            int nOffset = 0;
            for(int iLoop = 0; iLoop < 20; ++iLoop)
            {
                str = SprEngine.FillRefsUsingCache(str, ctx);

                int nStart = str.IndexOf(StrRefStart, nOffset, SprEngine.ScMethod);
                if(nStart < 0) break;
                int nEnd = str.IndexOf(StrRefEnd, nStart + 1, SprEngine.ScMethod);
                if(nEnd <= nStart) break;

                string strFullRef = str.Substring(nStart, nEnd - nStart + 1);
                char chScan, chWanted;
                PwEntry peFound = FindRefTarget(strFullRef, ctx, out chScan, out chWanted);

                if(peFound != null)
                {
                    string strInsData;
                    if(chWanted == 'T')
                        strInsData = peFound.Strings.ReadSafe(PwDefs.TitleField);
                    else if(chWanted == 'U')
                        strInsData = peFound.Strings.ReadSafe(PwDefs.UserNameField);
                    else if(chWanted == 'A')
                        strInsData = peFound.Strings.ReadSafe(PwDefs.UrlField);
                    else if(chWanted == 'P')
                        strInsData = peFound.Strings.ReadSafe(PwDefs.PasswordField);
                    else if(chWanted == 'N')
                        strInsData = peFound.Strings.ReadSafe(PwDefs.NotesField);
                    else if(chWanted == 'I')
                        strInsData = peFound.Uuid.ToHexString();
                    else { nOffset = nStart + 1; continue; }

                    if((chWanted == 'P') && !ctx.ForcePlainTextPasswords)
                        strInsData = PwDefs.HiddenPassword;

                    SprContext sprSub = ctx.WithoutContentTransformations();
                    sprSub.Entry = peFound;

                    string strInnerContent = SprEngine.CompileInternal(strInsData,
                        sprSub, uRecursionLevel + 1);
                    strInnerContent = SprEngine.TransformContent(strInnerContent, ctx);

                    // str = str.Substring(0, nStart) + strInnerContent + str.Substring(nEnd + 1);
                    SprEngine.AddRefToCache(strFullRef, strInnerContent, ctx);
                    str = SprEngine.FillRefsUsingCache(str, ctx);
                }
                else { nOffset = nStart + 1; continue; }
            }

            return str;
        }
Ejemplo n.º 20
0
        private static List <KeyValuePair <PwEntry, ulong> > CreatePwQualityListEx(
            PwDatabase pd, IStatusLogger sl)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return(null);
            }
            PwGroup pg = pd.RootGroup;

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

            uint uEntries     = pg.GetEntriesCount(true);
            uint uEntriesDone = 0;
            List <KeyValuePair <PwEntry, ulong> > l = new List <KeyValuePair <PwEntry, ulong> >();

            EntryHandler eh = delegate(PwEntry pe)
            {
                if ((sl != null) && (uEntries != 0))
                {
                    uint u = (uEntriesDone * 100) / uEntries;
                    if (!sl.SetProgress(u))
                    {
                        return(false);
                    }
                }
                ++uEntriesDone;                 // Also used for sorting, see below

                if (!pe.GetSearchingEnabled())
                {
                    return(true);
                }

                SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive);
                string     str = SprEngine.Compile(pe.Strings.ReadSafe(
                                                       PwDefs.PasswordField), ctx);
                if (str.Length != 0)
                {
                    uint q = QualityEstimation.EstimatePasswordBits(str.ToCharArray());
                    l.Add(new KeyValuePair <PwEntry, ulong>(pe,
                                                            ((ulong)q << 32) | (ulong)uEntriesDone));
                }

                return(true);
            };

            if (!pg.TraverseTree(TraversalMethod.PreOrder, null, eh))
            {
                return(null);
            }

            Comparison <KeyValuePair <PwEntry, ulong> > fCompare = delegate(
                KeyValuePair <PwEntry, ulong> x, KeyValuePair <PwEntry, ulong> y)
            {
                return(x.Value.CompareTo(y.Value));
            };

            l.Sort(fCompare);

            return(l);
        }
Ejemplo n.º 21
0
        public static PwEntry FindRefTarget(string strFullRef, SprContext ctx,
			out char chScan, out char chWanted)
        {
            chScan = char.MinValue;
            chWanted = char.MinValue;

            if(strFullRef == null) { Debug.Assert(false); return null; }
            if(!strFullRef.StartsWith(StrRefStart, SprEngine.ScMethod) ||
                !strFullRef.EndsWith(StrRefEnd, SprEngine.ScMethod))
                return null;
            if((ctx == null) || (ctx.Database == null)) { Debug.Assert(false); return null; }

            string strRef = strFullRef.Substring(StrRefStart.Length,
                strFullRef.Length - StrRefStart.Length - StrRefEnd.Length);
            if(strRef.Length <= 4) return null;
            if(strRef[1] != '@') return null;
            if(strRef[3] != ':') return null;

            chScan = char.ToUpper(strRef[2]);
            chWanted = char.ToUpper(strRef[0]);

            SearchParameters sp = SearchParameters.None;
            sp.SearchString = strRef.Substring(4);
            if(chScan == 'T') sp.SearchInTitles = true;
            else if(chScan == 'U') sp.SearchInUserNames = true;
            else if(chScan == 'A') sp.SearchInUrls = true;
            else if(chScan == 'P') sp.SearchInPasswords = true;
            else if(chScan == 'N') sp.SearchInNotes = true;
            else if(chScan == 'I') sp.SearchInUuids = true;
            else if(chScan == 'O') sp.SearchInOther = true;
            else return null;

            PwObjectList<PwEntry> lFound = new PwObjectList<PwEntry>();
            ctx.Database.RootGroup.SearchEntries(sp, lFound);

            return ((lFound.UCount > 0) ? lFound.GetAt(0) : null);
        }
Ejemplo n.º 22
0
        private string GenerateTotp(PwEntryDatabase item, string placeholder)
        {
            var ctx = new SprContext(item.entry, item.database, SprCompileFlags.All, false, false);

            return(SprEngine.Compile(placeholder, ctx));
        }
Ejemplo n.º 23
0
        private static List <EuSimilarPasswords> FindSimilarPasswordsEx(
            PwDatabase pd, IStatusLogger sl)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return(null);
            }
            PwGroup pg = pd.RootGroup;

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

            const uint uPrePct  = 33;
            const long cPostPct = 67;

            uint           uEntries     = pg.GetEntriesCount(true);
            uint           uEntriesDone = 0;
            List <PwEntry> lEntries     = new List <PwEntry>();
            List <string>  lPasswords   = new List <string>();

            EntryHandler eh = delegate(PwEntry pe)
            {
                if ((sl != null) && (uEntries != 0))
                {
                    uint u = (uEntriesDone * uPrePct) / uEntries;
                    if (!sl.SetProgress(u))
                    {
                        return(false);
                    }

                    ++uEntriesDone;
                }

                if (!pe.GetSearchingEnabled())
                {
                    return(true);
                }

                SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive);
                string     str = SprEngine.Compile(pe.Strings.ReadSafe(
                                                       PwDefs.PasswordField), ctx);
                if (str.Length != 0)
                {
                    lEntries.Add(pe);
                    lPasswords.Add(str);
                }

                return(true);
            };

            if (!pg.TraverseTree(TraversalMethod.PreOrder, null, eh))
            {
                return(null);
            }

            Debug.Assert(TextSimilarity.LevenshteinDistance("Columns", "Comments") == 4);
            Debug.Assert(TextSimilarity.LevenshteinDistance("File/URL", "Field Value") == 8);

            long cTotal = ((long)lEntries.Count * (long)(lEntries.Count - 1)) / 2L;
            long cDone  = 0;

            List <EuSimilarPasswords> l = new List <EuSimilarPasswords>();

            for (int i = 0; i < (lEntries.Count - 1); ++i)
            {
                string strA = lPasswords[i];
                Debug.Assert(strA.Length != 0);                 // See above

                for (int j = i + 1; j < lEntries.Count; ++j)
                {
                    string strB = lPasswords[j];

                    if (strA != strB)
                    {
                        l.Add(new EuSimilarPasswords(lEntries[i], lEntries[j], 1.0f -
                                                     ((float)TextSimilarity.LevenshteinDistance(strA, strB) /
                                                      (float)Math.Max(strA.Length, strB.Length))));
                    }

                    if (sl != null)
                    {
                        ++cDone;

                        uint u = uPrePct + (uint)((cDone * cPostPct) / cTotal);
                        if (!sl.SetProgress(u))
                        {
                            return(null);
                        }
                    }
                }
            }
            Debug.Assert((cDone == cTotal) || (sl == null));

            Comparison <EuSimilarPasswords> fCmp = delegate(EuSimilarPasswords x,
                                                            EuSimilarPasswords y)
            {
                return(y.Similarity.CompareTo(x.Similarity));                // Descending
            };

            l.Sort(fCmp);

            int ciMax = Math.Max(lEntries.Count / 2, 20);

            if (l.Count > ciMax)
            {
                l.RemoveRange(ciMax, l.Count - ciMax);
            }

            return(l);
        }
Ejemplo n.º 24
0
        public static string TransformContent(string strContent, SprContext ctx)
        {
            if(strContent == null) { Debug.Assert(false); return string.Empty; }

            string str = strContent;

            if(ctx != null)
            {
                if(ctx.EncodeQuotesForCommandLine)
                    str = SprEncoding.MakeCommandQuotes(str);

                if(ctx.EncodeAsAutoTypeSequence)
                    str = SprEncoding.MakeAutoTypeSequence(str);
            }

            return str;
        }
Ejemplo n.º 25
0
        private static string ReplacePickField(string strText, SprContext ctx)
        {
            string     str = strText;
            PwEntry    pe  = ((ctx != null) ? ctx.Entry : null);
            PwDatabase pd  = ((ctx != null) ? ctx.Database : null);

            while (true)
            {
                const string strPlh = @"{PICKFIELD}";
                int          p      = str.IndexOf(strPlh, StrUtil.CaseIgnoreCmp);
                if (p < 0)
                {
                    break;
                }

                string strRep = string.Empty;

                List <FpField> l = new List <FpField>();
                string         strGroup;

                if (pe != null)
                {
                    strGroup = KPRes.Entry + " - " + KPRes.StandardFields;

                    Debug.Assert(PwDefs.GetStandardFields().Count == 5);
                    l.Add(new FpField(KPRes.Title, pe.Strings.GetSafe(PwDefs.TitleField),
                                      strGroup));
                    l.Add(new FpField(KPRes.UserName, pe.Strings.GetSafe(PwDefs.UserNameField),
                                      strGroup));
                    l.Add(new FpField(KPRes.Password, pe.Strings.GetSafe(PwDefs.PasswordField),
                                      strGroup));
                    l.Add(new FpField(KPRes.Url, pe.Strings.GetSafe(PwDefs.UrlField),
                                      strGroup));
                    l.Add(new FpField(KPRes.Notes, pe.Strings.GetSafe(PwDefs.NotesField),
                                      strGroup));

                    strGroup = KPRes.Entry + " - " + KPRes.CustomFields;
                    foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings)
                    {
                        if (PwDefs.IsStandardField(kvp.Key))
                        {
                            continue;
                        }

                        l.Add(new FpField(kvp.Key, kvp.Value, strGroup));
                    }

                    PwGroup pg = pe.ParentGroup;
                    if (pg != null)
                    {
                        strGroup = KPRes.Group;

                        l.Add(new FpField(KPRes.Name, new ProtectedString(
                                              false, pg.Name), strGroup));

                        if (pg.Notes.Length > 0)
                        {
                            l.Add(new FpField(KPRes.Notes, new ProtectedString(
                                                  false, pg.Notes), strGroup));
                        }
                    }
                }

                if (pd != null)
                {
                    strGroup = KPRes.Database;

                    if (pd.Name.Length > 0)
                    {
                        l.Add(new FpField(KPRes.Name, new ProtectedString(
                                              false, pd.Name), strGroup));
                    }
                    l.Add(new FpField(KPRes.FileOrUrl, new ProtectedString(
                                          false, pd.IOConnectionInfo.Path), strGroup));
                }

                FpField fpf = FieldPickerForm.ShowAndRestore(KPRes.PickField,
                                                             KPRes.PickFieldDesc, l);
                if (fpf != null)
                {
                    strRep = fpf.Value.ReadString();
                }

                strRep = SprEngine.Compile(strRep, ctx.WithoutContentTransformations());
                strRep = SprEngine.TransformContent(strRep, ctx);

                str = str.Remove(p, strPlh.Length);
                str = str.Insert(p, strRep);
            }

            return(str);
        }
Ejemplo n.º 26
0
        private static void AddRefToCache(string strRef, string strValue,
			SprContext ctx)
        {
            if(strRef == null) { Debug.Assert(false); return; }
            if(strValue == null) { Debug.Assert(false); return; }
            if(ctx == null) { Debug.Assert(false); return; }

            // Only add if not exists, do not overwrite
            if(!ctx.RefsCache.ContainsKey(strRef))
                ctx.RefsCache.Add(strRef, strValue);
        }
Ejemplo n.º 27
0
        private static string CompileInternal(string strText, SprContext ctx,
			uint uRecursionLevel)
        {
            if(strText == null) { Debug.Assert(false); return string.Empty; }
            if(ctx == null) { Debug.Assert(false); ctx = new SprContext(); }

            if(uRecursionLevel >= SprEngine.MaxRecursionDepth)
            {
                Debug.Assert(false); // Most likely a recursive reference
                return string.Empty; // Do not return strText (endless loop)
            }

            string str = strText;

            bool bExt = ((ctx.Flags & (SprCompileFlags.ExtActive |
                SprCompileFlags.ExtNonActive)) != SprCompileFlags.None);
            if(bExt && (SprEngine.FilterCompilePre != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompilePre(null, args);
                str = args.Text;
            }

            if((ctx.Flags & SprCompileFlags.Comments) != SprCompileFlags.None)
                str = RemoveComments(str);

            if(ctx.Entry != null)
            {
                if((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
                    str = ReplacePickPw(str, ctx, uRecursionLevel);

                if((ctx.Flags & SprCompileFlags.EntryStrings) != SprCompileFlags.None)
                    str = FillEntryStrings(str, ctx, uRecursionLevel);

                if((ctx.Flags & SprCompileFlags.EntryStringsSpecial) != SprCompileFlags.None)
                {
                    // ctx.UrlRemoveSchemeOnce = true;
                    // str = SprEngine.FillIfExists(str, @"{URL:RMVSCM}",
                    //	ctx.Entry.Strings.GetSafe(PwDefs.UrlField), ctx, uRecursionLevel);
                    // Debug.Assert(!ctx.UrlRemoveSchemeOnce);

                    str = FillEntryStringsSpecial(str, ctx, uRecursionLevel);
                }

                if(((ctx.Flags & SprCompileFlags.PasswordEnc) != SprCompileFlags.None) &&
                    (str.IndexOf(@"{PASSWORD_ENC}", SprEngine.ScMethod) >= 0))
                    str = SprEngine.FillIfExists(str, @"{PASSWORD_ENC}", new ProtectedString(false,
                        StrUtil.EncryptString(ctx.Entry.Strings.ReadSafe(PwDefs.PasswordField))),
                        ctx, uRecursionLevel);

                if(((ctx.Flags & SprCompileFlags.Group) != SprCompileFlags.None) &&
                    (ctx.Entry.ParentGroup != null))
                {
                    str = SprEngine.FillIfExists(str, @"{GROUP}", new ProtectedString(
                        false, ctx.Entry.ParentGroup.Name), ctx, uRecursionLevel);

                    str = SprEngine.FillIfExists(str, @"{GROUPPATH}", new ProtectedString(
                        false, ctx.Entry.ParentGroup.GetFullPath()), ctx, uRecursionLevel);
                }
            }

            if(ctx.Database != null)
            {
                if((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
                {
                    // For backward compatibility only
                    str = SprEngine.FillIfExists(str, @"{DOCDIR}", new ProtectedString(
                        false, UrlUtil.GetFileDirectory(ctx.Database.IOConnectionInfo.Path,
                        false, false)), ctx, uRecursionLevel);

                    str = SprEngine.FillIfExists(str, @"{DB_PATH}", new ProtectedString(
                        false, ctx.Database.IOConnectionInfo.Path), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_DIR}", new ProtectedString(
                        false, UrlUtil.GetFileDirectory(ctx.Database.IOConnectionInfo.Path,
                        false, false)), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_NAME}", new ProtectedString(
                        false, UrlUtil.GetFileName(ctx.Database.IOConnectionInfo.Path)),
                        ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_BASENAME}", new ProtectedString(
                        false, UrlUtil.StripExtension(UrlUtil.GetFileName(
                        ctx.Database.IOConnectionInfo.Path))), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_EXT}", new ProtectedString(
                        false, UrlUtil.GetExtension(ctx.Database.IOConnectionInfo.Path)),
                        ctx, uRecursionLevel);
                }
            }

            if((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
            {
                str = SprEngine.FillIfExists(str, @"{ENV_DIRSEP}", new ProtectedString(
                    false, Path.DirectorySeparatorChar.ToString()), ctx, uRecursionLevel);

                string strPF86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                if(string.IsNullOrEmpty(strPF86))
                    strPF86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                if(strPF86 != null)
                    str = SprEngine.FillIfExists(str, @"{ENV_PROGRAMFILES_X86}",
                        new ProtectedString(false, strPF86), ctx, uRecursionLevel);
                else { Debug.Assert(false); }
            }

            if((ctx.Flags & SprCompileFlags.AutoType) != SprCompileFlags.None)
            {
                str = StrUtil.ReplaceCaseInsensitive(str, @"{CLEARFIELD}",
                    @"{HOME}+({END}){DEL}{DELAY 50}");
                str = StrUtil.ReplaceCaseInsensitive(str, @"{WIN}", @"{VKEY 91}");
                str = StrUtil.ReplaceCaseInsensitive(str, @"{LWIN}", @"{VKEY 91}");
                str = StrUtil.ReplaceCaseInsensitive(str, @"{RWIN}", @"{VKEY 92}");
                str = StrUtil.ReplaceCaseInsensitive(str, @"{APPS}", @"{VKEY 93}");

                for(int np = 0; np < 10; ++np)
                    str = StrUtil.ReplaceCaseInsensitive(str, @"{NUMPAD" +
                        Convert.ToString(np, 10) + @"}", @"{VKEY " +
                        Convert.ToString(np + 0x60, 10) + @"}");
            }

            if((ctx.Flags & SprCompileFlags.DateTime) != SprCompileFlags.None)
            {
                DateTime dtNow = DateTime.Now; // Local time
                str = SprEngine.FillIfExists(str, @"{DT_YEAR}", new ProtectedString(
                    false, dtNow.Year.ToString("D4")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_MONTH}", new ProtectedString(
                    false, dtNow.Month.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_DAY}", new ProtectedString(
                    false, dtNow.Day.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_HOUR}", new ProtectedString(
                    false, dtNow.Hour.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_MINUTE}", new ProtectedString(
                    false, dtNow.Minute.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_SECOND}", new ProtectedString(
                    false, dtNow.Second.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_SIMPLE}", new ProtectedString(
                    false, dtNow.ToString("yyyyMMddHHmmss")), ctx, uRecursionLevel);

                dtNow = dtNow.ToUniversalTime();
                str = SprEngine.FillIfExists(str, @"{DT_UTC_YEAR}", new ProtectedString(
                    false, dtNow.Year.ToString("D4")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_MONTH}", new ProtectedString(
                    false, dtNow.Month.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_DAY}", new ProtectedString(
                    false, dtNow.Day.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_HOUR}", new ProtectedString(
                    false, dtNow.Hour.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_MINUTE}", new ProtectedString(
                    false, dtNow.Minute.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_SECOND}", new ProtectedString(
                    false, dtNow.Second.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_SIMPLE}", new ProtectedString(
                    false, dtNow.ToString("yyyyMMddHHmmss")), ctx, uRecursionLevel);
            }

            if((ctx.Flags & SprCompileFlags.References) != SprCompileFlags.None)
                str = SprEngine.FillRefPlaceholders(str, ctx, uRecursionLevel);

            if(((ctx.Flags & SprCompileFlags.EnvVars) != SprCompileFlags.None) &&
                (str.IndexOf('%') >= 0))
            {
                // Replace environment variables
                foreach(DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    string strKey = (de.Key as string);
                    string strValue = (de.Value as string);

                    if((strKey != null) && (strValue != null))
                        str = SprEngine.FillIfExists(str, @"%" + strKey + @"%",
                            new ProtectedString(false, strValue), ctx, uRecursionLevel);
                    else { Debug.Assert(false); }
                }
            }

            str = EntryUtil.FillPlaceholders(str, ctx);

            if(bExt && (SprEngine.FilterCompile != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompile(null, args);
                str = args.Text;
            }

            if(ctx.EncodeAsAutoTypeSequence)
            {
                str = StrUtil.NormalizeNewLines(str, false);
                str = str.Replace("\n", @"{ENTER}");
            }

            return str;
        }
Ejemplo n.º 28
0
        private static string FillEntryStrings(string str, SprContext ctx,
			uint uRecursionLevel)
        {
            List<string> vKeys = ctx.Entry.Strings.GetKeys();

            // Ensure that all standard field names are in the list
            // (this is required in order to replace the standard placeholders
            // even if the corresponding standard field isn't present in
            // the entry)
            List<string> vStdNames = PwDefs.GetStandardFields();
            foreach(string strStdField in vStdNames)
            {
                if(!vKeys.Contains(strStdField)) vKeys.Add(strStdField);
            }

            // Do not directly enumerate the strings in ctx.Entry.Strings,
            // because strings might change during the Spr compilation
            foreach(string strField in vKeys)
            {
                string strKey = (PwDefs.IsStandardField(strField) ?
                    (@"{" + strField + @"}") :
                    (@"{" + PwDefs.AutoTypeStringPrefix + strField + @"}"));

                if(!ctx.ForcePlainTextPasswords && strKey.Equals(@"{" +
                    PwDefs.PasswordField + @"}", StrUtil.CaseIgnoreCmp))
                {
                    str = SprEngine.FillIfExists(str, strKey, new ProtectedString(
                        false, PwDefs.HiddenPassword), ctx, uRecursionLevel);
                    continue;
                }

                // Use GetSafe because the field doesn't necessarily exist
                // (might be a standard field that has been added above)
                str = SprEngine.FillIfExists(str, strKey, ctx.Entry.Strings.GetSafe(
                    strField), ctx, uRecursionLevel);
            }

            return str;
        }
Ejemplo n.º 29
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
                                                            SprContext ctx, uint uRecursionLevel)
        {
            PwEntry    pe = ctx.Entry;
            PwDatabase pd = ctx.Database;

            if ((pe == null) || (pd == null))
            {
                return(strText);
            }

            string str = strText;

            const string strNewPwStart = @"{NEWPASSWORD";

            if (str.IndexOf(strNewPwStart, StrUtil.CaseIgnoreCmp) < 0)
            {
                return(str);
            }

            string strGen = null;

            int           iStart;
            List <string> lParams;

            while (SprEngine.ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                                         strNewPwStart + ":", out iStart, out lParams, true))
            {
                if (strGen == null)
                {
                    strGen = GeneratePassword((((lParams != null) &&
                                                (lParams.Count > 0)) ? lParams[0] : string.Empty), ctx);
                }

                string strIns = SprEngine.TransformContent(strGen, ctx);
                str = str.Insert(iStart, strIns);
            }

            const string strNewPwPlh = strNewPwStart + @"}";

            if (str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                if (strGen == null)
                {
                    strGen = GeneratePassword(null, ctx);
                }

                string strIns = SprEngine.TransformContent(strGen, ctx);
                str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
            }

            if (strGen != null)
            {
                pe.CreateBackup(pd);

                ProtectedString psGen = new ProtectedString(
                    pd.MemoryProtection.ProtectPassword, strGen);
                pe.Strings.Set(PwDefs.PasswordField, psGen);

                pe.Touch(true, false);
                pd.Modified = true;
            }
            else
            {
                Debug.Assert(false);
            }

            return(str);
        }
Ejemplo n.º 30
0
        private static string FillEntryStringsSpecial(string str, SprContext ctx,
			uint uRecursionLevel)
        {
            if((str.IndexOf(UrlSpecialRmvScm, SprEngine.ScMethod) >= 0) ||
                (str.IndexOf(UrlSpecialScm, SprEngine.ScMethod) >= 0) ||
                (str.IndexOf(UrlSpecialHost, SprEngine.ScMethod) >= 0) ||
                (str.IndexOf(UrlSpecialPort, SprEngine.ScMethod) >= 0) ||
                (str.IndexOf(UrlSpecialPath, SprEngine.ScMethod) >= 0) ||
                (str.IndexOf(UrlSpecialQuery, SprEngine.ScMethod) >= 0))
            {
                string strUrl = SprEngine.FillIfExists(@"{URL}", @"{URL}",
                    ctx.Entry.Strings.GetSafe(PwDefs.UrlField), ctx, uRecursionLevel);

                str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialRmvScm,
                    UrlUtil.RemoveScheme(strUrl));

                try
                {
                    Uri uri = new Uri(strUrl);

                    str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialScm,
                        uri.Scheme);
                    str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialHost,
                        uri.Host);
                    str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialPort,
                        uri.Port.ToString());
                    str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialPath,
                        uri.AbsolutePath);
                    str = StrUtil.ReplaceCaseInsensitive(str, UrlSpecialQuery,
                        uri.Query);
                }
                catch(Exception) { } // Invalid URI
            }

            return str;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Notify Icon Context Menu Opening.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNotifyMenuOpening(object sender, CancelEventArgs e)
        {
            foreach (var Menu in niMenuList)
            {
                m_host.MainWindow.TrayContextMenu.Items.Remove(Menu);
            }
            niMenuList.Clear();
            if (m_host.CustomConfig.GetBool(setname_bool_NotifyContext_Visible, true))
            {
                niMenuTitle.Visible     = true;
                niMenuSeperator.Visible = true;
                if (m_host.MainWindow.ActiveDatabase.IsOpen)
                {
                    var trimTrayText = m_host.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);
                    foreach (PwEntry Entry in m_host.MainWindow.ActiveDatabase.RootGroup.GetEntries(true))
                    {
                        if (SettingsCheck(Entry) && SeedCheck(Entry))
                        {
                            var entryTitle = Entry.Strings.ReadSafe(PwDefs.TitleField);

                            var    context       = new SprContext(Entry, m_host.MainWindow.ActiveDatabase, SprCompileFlags.All, false, false);
                            var    entryUsername = SprEngine.Compile(Entry.Strings.ReadSafe(PwDefs.UserNameField), context);
                            string trayTitle;
                            if (trimTrayText && entryTitle.Length + entryUsername.Length > setstat_trim_text_length)
                            {
                                trayTitle = entryTitle.ExtWithSpaceAfter();
                            }
                            else
                            {
                                trayTitle = entryTitle.ExtWithSpaceAfter() + entryUsername.ExtWithParenthesis();
                            }
                            m_host.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);

                            var NewMenu = new ToolStripMenuItem(trayTitle, Properties.Resources.TOTP_Key, OnNotifyMenuTOTPClick);
                            NewMenu.Tag = Entry;
                            if (!SettingsValidate(Entry))
                            {
                                NewMenu.Enabled = false;
                                NewMenu.Image   = Properties.Resources.TOTP_Error;
                            }
                            niMenuList.Add(NewMenu);
                        }
                    }
                    if (niMenuList.Count > 0)
                    {
                        niMenuList.Sort((p1, p2) => string.Compare(p1.Text, p2.Text, true));
                        for (int i = 0; i <= niMenuList.Count - 1; i++)
                        {
                            m_host.MainWindow.TrayContextMenu.Items.Insert(i + 1, niMenuList[i]);
                        }
                    }
                    else
                    {
                        var NewMenu = new ToolStripMenuItem(TrayTOTP_Plugin_Localization.strNoTOTPFound);
                        NewMenu.Image = Properties.Resources.TOTP_None;
                        niMenuList.Add(NewMenu);
                        m_host.MainWindow.TrayContextMenu.Items.Insert(1, niMenuList[0]);
                    }
                }
                else
                {
                    if (m_host.MainWindow.IsFileLocked(null))
                    {
                        var NewMenu = new ToolStripMenuItem(TrayTOTP_Plugin_Localization.strDatabaseIsLocked);
                        NewMenu.Image = Properties.Resources.TOTP_Lock;
                        niMenuList.Add(NewMenu);
                        m_host.MainWindow.TrayContextMenu.Items.Insert(1, niMenuList[0]);
                    }
                    else
                    {
                        var NewMenu = new ToolStripMenuItem(TrayTOTP_Plugin_Localization.strDatabaseNotOpen);
                        NewMenu.Image = Properties.Resources.TOTP_Error;
                        niMenuList.Add(NewMenu);
                        m_host.MainWindow.TrayContextMenu.Items.Insert(1, niMenuList[0]);
                    }
                }
            }
            else
            {
                niMenuTitle.Visible     = false;
                niMenuSeperator.Visible = false;
            }
        }
Ejemplo n.º 32
0
        private static string FillIfExists(string strData, string strPlaceholder,
			ProtectedString psParsable, SprContext ctx, uint uRecursionLevel)
        {
            // // The UrlRemoveSchemeOnce property of ctx must be cleared
            // // before this method returns and before any recursive call
            // bool bRemoveScheme = false;
            // if(ctx != null)
            // {
            //	bRemoveScheme = ctx.UrlRemoveSchemeOnce;
            //	ctx.UrlRemoveSchemeOnce = false;
            // }

            if(strData == null) { Debug.Assert(false); return string.Empty; }
            if(strPlaceholder == null) { Debug.Assert(false); return strData; }
            if(strPlaceholder.Length == 0) { Debug.Assert(false); return strData; }
            if(psParsable == null) { Debug.Assert(false); return strData; }

            if(strData.IndexOf(strPlaceholder, SprEngine.ScMethod) >= 0)
            {
                string strReplacement = SprEngine.CompileInternal(
                    psParsable.ReadString(), ctx.WithoutContentTransformations(),
                    uRecursionLevel + 1);

                // if(bRemoveScheme)
                //	strReplacement = UrlUtil.RemoveScheme(strReplacement);

                return SprEngine.FillPlaceholder(strData, strPlaceholder,
                    strReplacement, ctx);
            }

            return strData;
        }
Ejemplo n.º 33
0
        // Multiple calls of this method are wrapped in
        // GetSequencesForWindowBegin and GetSequencesForWindowEnd
        private static List <string> GetSequencesForWindow(PwEntry pwe,
                                                           IntPtr hWnd, string strWindow, PwDatabase pdContext, int iEventID)
        {
            List <string> l = new List <string>();

            if (pwe == null)
            {
                Debug.Assert(false); return(l);
            }
            if (strWindow == null)
            {
                Debug.Assert(false); return(l);
            }                                                                    // May be empty

            if (!pwe.GetAutoTypeEnabled())
            {
                return(l);
            }

            SprContext sprCtx = new SprContext(pwe, pdContext,
                                               SprCompileFlags.NonActive);

            RaiseSequenceQueryEvent(AutoType.SequenceQueryPre, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            // Specifically defined sequences must match before the title,
            // in order to allow selecting the first item as default one
            foreach (AutoTypeAssociation a in pwe.AutoType.Associations)
            {
                string strWndSpec = a.WindowName;
                if (strWndSpec == null)
                {
                    Debug.Assert(false); continue;
                }

                strWndSpec = SprEngine.Compile(strWndSpec.Trim(), sprCtx);

                if (MatchWindows(strWndSpec, strWindow))
                {
                    string strSeq = a.Sequence;
                    if (string.IsNullOrEmpty(strSeq))
                    {
                        strSeq = pwe.GetAutoTypeSequence();
                    }
                    AddSequence(l, strSeq);
                }
            }

            RaiseSequenceQueryEvent(AutoType.SequenceQuery, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            if (Program.Config.Integration.AutoTypeMatchByTitle)
            {
                string strTitle = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                        PwDefs.TitleField).Trim(), sprCtx);
                if ((strTitle.Length > 0) && (strWindow.IndexOf(strTitle,
                                                                StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            string strCmpUrl = null;             // To cache compiled URL

            if (Program.Config.Integration.AutoTypeMatchByUrlInTitle)
            {
                strCmpUrl = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                  PwDefs.UrlField).Trim(), sprCtx);
                if ((strCmpUrl.Length > 0) && (strWindow.IndexOf(strCmpUrl,
                                                                 StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            if (Program.Config.Integration.AutoTypeMatchByUrlHostInTitle)
            {
                if (strCmpUrl == null)
                {
                    strCmpUrl = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                      PwDefs.UrlField).Trim(), sprCtx);
                }

                string strCleanUrl = StrUtil.RemovePlaceholders(strCmpUrl);
                string strHost     = UrlUtil.GetHost(strCleanUrl);

                if (strHost.StartsWith("www.", StrUtil.CaseIgnoreCmp) &&
                    (strCleanUrl.StartsWith("http:", StrUtil.CaseIgnoreCmp) ||
                     strCleanUrl.StartsWith("https:", StrUtil.CaseIgnoreCmp)))
                {
                    strHost = strHost.Substring(4);
                }

                if ((strHost.Length > 0) && (strWindow.IndexOf(strHost,
                                                               StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            if (Program.Config.Integration.AutoTypeMatchByTagInTitle)
            {
                foreach (string strTag in pwe.Tags)
                {
                    if (string.IsNullOrEmpty(strTag))
                    {
                        Debug.Assert(false); continue;
                    }

                    if (strWindow.IndexOf(strTag, StrUtil.CaseIgnoreCmp) >= 0)
                    {
                        AddSequence(l, pwe.GetAutoTypeSequence());
                        break;
                    }
                }
            }

            RaiseSequenceQueryEvent(AutoType.SequenceQueryPost, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            return(l);
        }
Ejemplo n.º 34
0
        private static string FillPlaceholder(string strData, string strPlaceholder,
			string strReplaceWith, SprContext ctx)
        {
            if(strData == null) { Debug.Assert(false); return string.Empty; }
            if(strPlaceholder == null) { Debug.Assert(false); return strData; }
            if(strPlaceholder.Length == 0) { Debug.Assert(false); return strData; }
            if(strReplaceWith == null) { Debug.Assert(false); return strData; }

            return StrUtil.ReplaceCaseInsensitive(strData, strPlaceholder,
                SprEngine.TransformContent(strReplaceWith, ctx));
        }
Ejemplo n.º 35
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);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Notify Icon Context Menu Opening.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNotifyMenuOpening(object sender, CancelEventArgs e)
        {
            foreach (var menu in _niMenuList)
            {
                PluginHost.MainWindow.TrayContextMenu.Items.Remove(menu);
            }
            _niMenuList.Clear();
            if (PluginHost.CustomConfig.GetBool(setname_bool_NotifyContext_Visible, true))
            {
                _niMenuTitle.Visible     = true;
                _niMenuSeperator.Visible = true;
                if (PluginHost.MainWindow.ActiveDatabase.IsOpen)
                {
                    var trimTrayText = PluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);
                    foreach (PwEntry entry in GetVisibleAndValidPasswordEntries())
                    {
                        var entryTitle = entry.Strings.ReadSafe(PwDefs.TitleField);

                        var    context       = new SprContext(entry, PluginHost.MainWindow.ActiveDatabase, SprCompileFlags.All, false, false);
                        var    entryUsername = SprEngine.Compile(entry.Strings.ReadSafe(PwDefs.UserNameField), context);
                        string trayTitle;
                        if ((trimTrayText && entryTitle.Length + entryUsername.Length > setstat_trim_text_length) || string.IsNullOrEmpty(entryUsername))
                        {
                            trayTitle = entryTitle.ExtWithSpaceAfter();
                        }
                        else
                        {
                            trayTitle = entryTitle.ExtWithSpaceAfter() + entryUsername.ExtWithParenthesis();
                        }
                        PluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);

                        var newMenu = new ToolStripMenuItem(trayTitle, Properties.Resources.TOTP_Key, OnNotifyMenuTOTPClick);
                        newMenu.Tag = entry;
                        if (!SettingsValidate(entry))
                        {
                            newMenu.Enabled = false;
                            newMenu.Image   = Properties.Resources.TOTP_Error;
                        }
                        _niMenuList.Add(newMenu);
                    }
                    if (_niMenuList.Count > 0)
                    {
                        _niMenuList.Sort((p1, p2) => string.Compare(p1.Text, p2.Text, true));
                        for (int i = 0; i <= _niMenuList.Count - 1; i++)
                        {
                            PluginHost.MainWindow.TrayContextMenu.Items.Insert(i + 1, _niMenuList[i]);
                        }
                    }
                    else
                    {
                        var newMenu = new ToolStripMenuItem(Localization.Strings.NoTOTPSeedFound);
                        newMenu.Image = Properties.Resources.TOTP_None;
                        _niMenuList.Add(newMenu);
                        PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
                    }

                    CreateMenuItemForOtherDatabases(_niMenuList);
                }
                else
                {
                    if (PluginHost.MainWindow.IsFileLocked(null))
                    {
                        var newMenu = new ToolStripMenuItem(Localization.Strings.DatabaseIsLocked);
                        newMenu.Image = Properties.Resources.TOTP_Lock;
                        _niMenuList.Add(newMenu);
                        PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
                    }
                    else
                    {
                        var newMenu = new ToolStripMenuItem(Localization.Strings.DatabaseIsNotOpen);
                        newMenu.Image = Properties.Resources.TOTP_Error;
                        _niMenuList.Add(newMenu);
                        PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
                    }
                }
            }
            else
            {
                _niMenuTitle.Visible     = false;
                _niMenuSeperator.Visible = false;
            }
        }