示例#1
0
        /// <summary>
        /// Write entries to a stream.
        /// </summary>
        /// <param name="msOutput">Output stream to which the entries will be written.</param>
        /// <param name="pwDatabase">Source database.</param>
        /// <param name="vEntries">Entries to serialize.</param>
        /// <returns>Returns <c>true</c>, if the entries were written successfully to the stream.</returns>
        public static bool WriteEntries(Stream msOutput, PwDatabase pwDatabase, PwEntry[] vEntries)
        {
            Kdb4File f = new Kdb4File(pwDatabase);
            f.m_format = Kdb4Format.PlainXml;

            XmlTextWriter xtw = null;
            try { xtw = new XmlTextWriter(msOutput, Encoding.UTF8); }
            catch(Exception) { Debug.Assert(false); return false; }
            if(xtw == null) { Debug.Assert(false); return false; }

            f.m_xmlWriter = xtw;

            xtw.Formatting = Formatting.Indented;
            xtw.IndentChar = '\t';
            xtw.Indentation = 1;

            xtw.WriteStartDocument(true);
            xtw.WriteStartElement(ElemRoot);

            foreach(PwEntry pe in vEntries)
                f.WriteEntry(pe, false);

            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Flush();
            xtw.Close();
            return true;
        }
示例#2
0
        /// <summary>
        /// Read entries from a stream.
        /// </summary>
        /// <param name="pwDatabase">Source database.</param>
        /// <param name="msData">Input stream to read the entries from.</param>
        /// <returns>Extracted entries.</returns>
        public static List<PwEntry> ReadEntries(PwDatabase pwDatabase, Stream msData)
        {
            Kdb4File f = new Kdb4File(pwDatabase);
            f.m_format = Kdb4Format.PlainXml;

            XmlDocument doc = new XmlDocument();
            doc.Load(msData);

            XmlElement el = doc.DocumentElement;
            if(el.Name != ElemRoot) throw new FormatException();

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

            foreach(XmlNode xmlChild in el.ChildNodes)
            {
                if(xmlChild.Name == ElemEntry)
                {
                    PwEntry pe = f.ReadEntry(xmlChild);
                    pe.Uuid = new PwUuid(true);

                    foreach(PwEntry peHistory in pe.History)
                        peHistory.Uuid = pe.Uuid;

                    vEntries.Add(pe);
                }
                else { Debug.Assert(false); }
            }

            return vEntries;
        }
示例#3
0
        private static void ExportDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);
            // if(string.IsNullOrEmpty(strPath)) return; // Allow no-file exports
            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            string strGroup = EcasUtil.GetParamString(a.Parameters, 2, true);
            string strTag   = EcasUtil.GetParamString(a.Parameters, 3, true);

            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            PwGroup pg = pd.RootGroup;

            if (!string.IsNullOrEmpty(strGroup))
            {
                char    chSep = strGroup[0];
                PwGroup pgSub = pg.FindCreateSubTree(strGroup.Substring(1),
                                                     new char[] { chSep }, false);
                pg = (pgSub ?? (new PwGroup(true, true, KPRes.Group, PwIcon.Folder)));
            }

            if (!string.IsNullOrEmpty(strTag))
            {
                // Do not use pg.Duplicate, because this method
                // creates new UUIDs
                pg = pg.CloneDeep();
                pg.TakeOwnership(true, true, true);

                GroupHandler gh = delegate(PwGroup pgSub)
                {
                    PwObjectList <PwEntry> l = pgSub.Entries;
                    long n = (long)l.UCount;
                    for (long i = n - 1; i >= 0; --i)
                    {
                        if (!l.GetAt((uint)i).HasTag(strTag))
                        {
                            l.RemoveAt((uint)i);
                        }
                    }

                    return(true);
                };

                gh(pg);
                pg.TraverseTree(TraversalMethod.PreOrder, gh, null);
            }

            PwExportInfo     pei = new PwExportInfo(pg, pd, true);
            IOConnectionInfo ioc = (!string.IsNullOrEmpty(strPath) ?
                                    IOConnectionInfo.FromPath(strPath) : null);

            ExportUtil.Export(pei, strFormat, ioc);
        }
示例#4
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            CsvStreamReader csv = new CsvStreamReader(strData, true);
            Dictionary <string, PwGroup> dictGroups = new Dictionary <string, PwGroup>();

            while (true)
            {
                string[] vLine = csv.ReadLine();
                if (vLine == null)
                {
                    break;
                }
                if (vLine.Length == 0)
                {
                    continue;                                   // Skip empty line
                }
                if (vLine.Length == 5)
                {
                    continue;                                   // Skip header line
                }
                if (vLine.Length != 34)
                {
                    Debug.Assert(false); continue;
                }

                string strType = vLine[0].Trim();
                if (strType.Equals("Is Template", StrUtil.CaseIgnoreCmp))
                {
                    continue;
                }
                if (strType.Equals("1"))
                {
                    continue;                                     // Skip template
                }
                string  strGroup = vLine[2].Trim();
                PwGroup pg;
                if (strGroup.Length == 0)
                {
                    pg = pwStorage.RootGroup;
                }
                else
                {
                    if (dictGroups.ContainsKey(strGroup))
                    {
                        pg = dictGroups[strGroup];
                    }
                    else
                    {
                        pg = new PwGroup(true, true, strGroup, PwIcon.Folder);
                        pwStorage.RootGroup.AddGroup(pg, true);
                        dictGroups[strGroup] = pg;
                    }
                }

                PwEntry pe = new PwEntry(true, true);
                pg.AddEntry(pe, true);

                string strTitle = vLine[1].Trim();
                if (strTitle.Length > 0)
                {
                    ImportUtil.AppendToField(pe, PwDefs.TitleField, strTitle, pwStorage);
                }

                for (int i = 0; i < 10; ++i)
                {
                    string strKey   = vLine[(i * 3) + 3].Trim();
                    string strValue = vLine[(i * 3) + 4].Trim();
                    if ((strKey.Length == 0) || (strValue.Length == 0))
                    {
                        continue;
                    }

                    string strMapped = ImportUtil.MapNameToStandardField(strKey, true);
                    if (string.IsNullOrEmpty(strMapped))
                    {
                        strMapped = strKey;
                    }
                    ImportUtil.AppendToField(pe, strMapped, strValue, pwStorage);
                }

                string strNotesPre = pe.Strings.ReadSafe(PwDefs.NotesField);
                string strNotes    = vLine[33].Trim();
                if (strNotes.Length > 0)
                {
                    if (strNotesPre.Length == 0)
                    {
                        ImportUtil.AppendToField(pe, PwDefs.NotesField, strNotes, pwStorage);
                    }
                    else
                    {
                        pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                           ((pwStorage == null) ? false :
                                            pwStorage.MemoryProtection.ProtectNotes), strNotesPre +
                                           Environment.NewLine + Environment.NewLine + strNotes));
                    }
                }
            }
        }
示例#5
0
 public override void PopulateEntry(PwEntry pwEntry, PwDatabase pwDatabase, UserPrefs userPrefs)
 {
     base.PopulateEntry(pwEntry, pwDatabase, userPrefs);
     pwEntry.IconId = PwIcon.Homebanking;
 }
示例#6
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            string[] vLines = strData.Split(new char[] { '\r', '\n' });

            PwGroup pg = pwStorage.RootGroup;
            PwEntry pe = new PwEntry(true, true);

            foreach (string strLine in vLines)
            {
                if (strLine.StartsWith(InitGroup))
                {
                    string strGroup = strLine.Remove(0, InitGroup.Length);
                    if (strGroup.Length > InitGroup.Length)
                    {
                        strGroup = strGroup.Substring(0, strGroup.Length - InitGroup.Length);
                    }

                    pg = pwStorage.RootGroup.FindCreateGroup(strGroup, true);

                    pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);
                }
                else if (strLine.StartsWith(InitNewEntry))
                {
                    pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);
                }
                else if (strLine.StartsWith(InitTitle))
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle,
                                       strLine.Remove(0, InitTitle.Length)));
                }
                else if (strLine.StartsWith(InitUser))
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName,
                                       strLine.Remove(0, InitUser.Length)));
                }
                else if (strLine.StartsWith(InitPassword))
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       strLine.Remove(0, InitPassword.Length)));
                }
                else if (strLine.StartsWith(InitURL))
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl,
                                       strLine.Remove(0, InitURL.Length)));
                }
                else if (strLine.StartsWith(InitEMail))
                {
                    pe.Strings.Set("E-Mail", new ProtectedString(
                                       false,
                                       strLine.Remove(0, InitEMail.Length)));
                }
                else if (strLine.StartsWith(InitNotes))
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       strLine.Remove(0, InitNotes.Length)));
                }
                else if (strLine.StartsWith(ContinueNotes))
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       pe.Strings.ReadSafe(PwDefs.NotesField) + "\r\n" +
                                       strLine.Remove(0, ContinueNotes.Length)));
                }
            }
        }
 /// <summary>
 /// Saves the provided OneDrive Refresh Token in the provided KeePass database
 /// </summary>
 /// <param name="keePassDatabase">KeePass database instance to store the Refresh Token in</param>
 /// <param name="refreshToken">The OneDrive Refresh Token to store securely in the KeePass database</param>
 public static void SaveRefreshTokenInKeePassDatabase(PwDatabase keePassDatabase, string refreshToken)
 {
     keePassDatabase.CustomData.Set("KoenZomers.KeePass.OneDriveSync.RefreshToken", refreshToken);
 }
示例#8
0
		/// <summary>
		/// Read entries from a stream.
		/// </summary>
		/// <param name="msData">Input stream to read the entries from.</param>
		/// <param name="pdContext">Context database (e.g. for storing icons).</param>
		/// <param name="bCopyIcons">If <c>true</c>, custom icons required by
		/// the loaded entries are copied to the context database.</param>
		/// <returns>Loaded entries.</returns>
		public static List<PwEntry> ReadEntries(Stream msData, PwDatabase pdContext,
			bool bCopyIcons)
		{
			List<PwEntry> lEntries = new List<PwEntry>();

			if(msData == null) { Debug.Assert(false); return lEntries; }
			// pdContext may be null

			/* KdbxFile f = new KdbxFile(pwDatabase);
			f.m_format = KdbxFormat.PlainXml;

			XmlDocument doc = new XmlDocument();
			doc.Load(msData);

			XmlElement el = doc.DocumentElement;
			if(el.Name != ElemRoot) throw new FormatException();

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

			foreach(XmlNode xmlChild in el.ChildNodes)
			{
				if(xmlChild.Name == ElemEntry)
				{
					PwEntry pe = f.ReadEntry(xmlChild);
					pe.Uuid = new PwUuid(true);

					foreach(PwEntry peHistory in pe.History)
						peHistory.Uuid = pe.Uuid;

					vEntries.Add(pe);
				}
				else { Debug.Assert(false); }
			}

			return vEntries; */

			PwDatabase pd = new PwDatabase();
			pd.New(new IOConnectionInfo(), new CompositeKey());

			KdbxFile f = new KdbxFile(pd);
			f.Load(msData, KdbxFormat.PlainXml, null);

			foreach(PwEntry pe in pd.RootGroup.Entries)
			{
				pe.SetUuid(new PwUuid(true), true);
				lEntries.Add(pe);

				if(bCopyIcons && (pdContext != null))
				{
					PwUuid pu = pe.CustomIconUuid;
					if(!pu.Equals(PwUuid.Zero))
					{
						int iSrc = pd.GetCustomIconIndex(pu);
						int iDst = pdContext.GetCustomIconIndex(pu);

						if(iSrc < 0) { Debug.Assert(false); }
						else if(iDst < 0)
						{
							pdContext.CustomIcons.Add(pd.CustomIcons[iSrc]);

							pdContext.Modified = true;
							pdContext.UINeedsIconUpdate = true;
						}
					}
				}
			}

			return lEntries;
		}
示例#9
0
        public static bool WriteEntries(Stream msOutput, PwDatabase pwDatabase,
			PwEntry[] vEntries)
        {
            return WriteEntries(msOutput, vEntries);
        }
示例#10
0
        /// <summary>
        /// Perform all kind of migrations between different KeePassOTP versions
        /// </summary>
        /// <param name="db"></param>
        /// <returns>true if something was migrated, false if nothing was done</returns>
        private static bool CheckAndMigrate(PwDatabase db, OTP_Migrations omFlags)
        {
            const string Migration_EntryDB = "KeePassOTP.MigrationStatus";
            const string Migration_OTPDB   = "KeePassOTPDB.MigrationStatus";
            string       sMigrationStatus  = string.Empty;
            bool         bMigrated         = false;


            //Get DB to work on
            OTPDAO.OTPHandler_DB h = GetOTPHandler(db);
            if (h != null)
            {
                sMigrationStatus = Migration_OTPDB;
            }
            else
            {
                sMigrationStatus = Migration_EntryDB;
            }

            OTP_Migrations omStatusOld = OTP_Migrations.None;

            if (!OTP_Migrations.TryParse(db.CustomData.Get(sMigrationStatus), out omStatusOld))
            {
                omStatusOld = OTP_Migrations.None;
            }
            OTP_Migrations omStatusNew = omStatusOld;

            if (MigrationRequired(OTP_Migrations.Entry2CustomData, omFlags, omStatusOld))
            {
                if (!db.UseDBForOTPSeeds() || !db.CustomData.Exists(OTPDAO.OTPHandler_DB.DBNAME))
                {
                    PwEntry pe = OTPHandler_DB.GetOTPDBEntry(db);
                    if (pe != null)
                    {
                        bMigrated = true;
                        OTPDAO.MigrateToCustomdata(db, pe);
                    }
                }
                omStatusNew |= OTP_Migrations.Entry2CustomData;
            }

            if (MigrationRequired(OTP_Migrations.KeePassOTP2OtpAuth, omFlags, omStatusOld))
            {
                int r = CheckOTPDataMigration(db);
                bMigrated |= r > 0;
                if (r >= 0)
                {
                    omStatusNew |= OTP_Migrations.KeePassOTP2OtpAuth;
                }
            }

            if (MigrationRequired(OTP_Migrations.SanitizeSeed, omFlags, omStatusOld))
            {
                int r = SanitizeSeeds(db);
                bMigrated |= r > 0;
                if (r >= 0)
                {
                    omStatusNew |= OTP_Migrations.SanitizeSeed;
                }
            }

            if (MigrationRequired(OTP_Migrations.OTPAuthFormatCorrection, omFlags, omStatusOld))
            {
                int r = OTPAuthFormatCorrection(db);
                bMigrated |= r > 0;
                if (r >= 0)
                {
                    omStatusNew |= OTP_Migrations.OTPAuthFormatCorrection;
                }
            }

            if (MigrationRequired(OTP_Migrations.CleanOTPDB, omFlags, omStatusOld))
            {
                int r = CleanOTPDB(db);
                bMigrated |= r > 0;
                if (r >= 0)
                {
                    omStatusNew |= OTP_Migrations.CleanOTPDB;
                }
            }

            if (MigrationRequired(OTP_Migrations.ProcessReferences, omFlags, omStatusOld))
            {
                int r = ProcessReferences(db);
                bMigrated |= r > 0;
                if (r >= 0)
                {
                    omStatusNew |= OTP_Migrations.ProcessReferences;
                }
            }

            if ((omStatusNew != omStatusOld) || bMigrated)
            {
                db.CustomData.Set(sMigrationStatus, omStatusNew.ToString());
                db.SettingsChanged = DateTime.UtcNow;
                db.Modified        = true;
                Program.MainForm.UpdateUI(false, null, false, null, false, null, Program.MainForm.ActiveDatabase == db);
            }
            return(bMigrated);
        }
示例#11
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            slLogger.SetText("> Spamex.com...", LogStatusType.Info);

            SingleLineEditForm dlgUser = new SingleLineEditForm();

            dlgUser.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.UserName,
                           KPRes.UserNamePrompt, KeePass.Properties.Resources.B48x48_WWW,
                           string.Empty, null);
            if (UIUtil.ShowDialogNotValue(dlgUser, DialogResult.OK))
            {
                return;
            }
            string strUser = dlgUser.ResultString;

            UIUtil.DestroyForm(dlgUser);

            SingleLineEditForm dlgPassword = new SingleLineEditForm();

            dlgPassword.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.Password,
                               KPRes.PasswordPrompt, KeePass.Properties.Resources.B48x48_WWW,
                               string.Empty, null);
            if (UIUtil.ShowDialogNotValue(dlgPassword, DialogResult.OK))
            {
                return;
            }
            string strPassword = dlgPassword.ResultString;

            UIUtil.DestroyForm(dlgPassword);

            RemoteCertificateValidationCallback pPrevCertCb =
                ServicePointManager.ServerCertificateValidationCallback;

            ServicePointManager.ServerCertificateValidationCallback =
                delegate(object sender, X509Certificate certificate, X509Chain chain,
                         SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };

            try
            {
                slLogger.SetText(KPRes.ImportingStatusMsg, LogStatusType.Info);

                string strPostData = @"toollogin=&MetaDomain=&LoginEmail=" +
                                     strUser + @"&LoginPassword="******"&Remember=1";

                List <KeyValuePair <string, string> > vCookies;
                string strMain = NetUtil.WebPageLogin(new Uri(UrlLoginPage),
                                                      strPostData, out vCookies);

                if (strMain.IndexOf("Welcome <b>" + strUser + "</b>") < 0)
                {
                    MessageService.ShowWarning(KPRes.InvalidUserPassword);
                    return;
                }

                string strIndexPage = NetUtil.WebPageGetWithCookies(new Uri(UrlIndexPage),
                                                                    vCookies, UrlDomain);

                ImportIndex(pwStorage, strIndexPage, vCookies, slLogger);

                int           nOffset   = 0;
                List <string> vSubPages = new List <string>();
                while (true)
                {
                    string strLink = StrUtil.GetStringBetween(strIndexPage, nOffset,
                                                              StrTabLinksStart, StrTabLinksEnd, out nOffset);
                    ++nOffset;

                    if (strLink.Length == 0)
                    {
                        break;
                    }

                    if (!strLink.StartsWith(StrTabLinkUrl))
                    {
                        continue;
                    }
                    if (vSubPages.IndexOf(strLink) >= 0)
                    {
                        continue;
                    }

                    vSubPages.Add(strLink);

                    string strSubPage = NetUtil.WebPageGetWithCookies(new Uri(
                                                                          UrlBase + strLink), vCookies, UrlDomain);

                    ImportIndex(pwStorage, strSubPage, vCookies, slLogger);
                }
            }
            finally
            {
                ServicePointManager.ServerCertificateValidationCallback = pPrevCertCb;
            }
        }
示例#12
0
        private static void ImportAccount(PwDatabase pwStorage, string strID,
                                          List <KeyValuePair <string, string> > vCookies, IStatusLogger slf)
        {
            string strPage = NetUtil.WebPageGetWithCookies(new Uri(
                                                               UrlAccountPage + strID), vCookies, UrlDomain);

            PwEntry pe = new PwEntry(true, true);

            pwStorage.RootGroup.AddEntry(pe, true);

            string str;

            string strTitle = StrUtil.GetStringBetween(strPage, 0, "Subject : <b>", "</b>");

            if (strTitle.StartsWith("<b>"))
            {
                strTitle = strTitle.Substring(3, strTitle.Length - 3);
            }
            pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectTitle, strTitle));

            string strUser = StrUtil.GetStringBetween(strPage, 0, "Site Username : <b>", "</b>");

            if (strUser.StartsWith("<b>"))
            {
                strUser = strUser.Substring(3, strUser.Length - 3);
            }
            pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectUserName, strUser));

            str = StrUtil.GetStringBetween(strPage, 0, "Site Password : <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectPassword, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Site Domain : <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectUrl, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Notes : <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectNotes, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Address:&nbsp;</td><td><font class=\"midHD\">", "</font></td>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Address", new ProtectedString(false, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Forwards to: <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Forward To", new ProtectedString(false, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Reply-To Messages: <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Reply-To Messages", new ProtectedString(false, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Allow Reply From: <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Allow Reply From", new ProtectedString(false, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Filter Mode: <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Filter Mode", new ProtectedString(false, str));

            str = StrUtil.GetStringBetween(strPage, 0, "Created: <b>", "</b>");
            if (str.StartsWith("<b>"))
            {
                str = str.Substring(3, str.Length - 3);
            }
            pe.Strings.Set("Created", new ProtectedString(false, str));

            slf.SetText(strTitle + " - " + strUser + " (" + strID + ")",
                        LogStatusType.Info);

            if (!slf.ContinueWork())
            {
                throw new InvalidOperationException(string.Empty);
            }
        }
示例#13
0
        private static string GenerateHtml(PwDatabase pd, string strName)
        {
            bool   bRtl        = Program.Translation.Properties.RightToLeft;
            string strLogLeft  = (bRtl ? "right" : "left");
            string strLogRight = (bRtl ? "left" : "right");

            GFunc <string, string> h  = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };
            GFunc <string, string> ltrPath = delegate(string str)
            {
                return(bRtl ? StrUtil.EnsureLtrPath(str) : str);
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
            sb.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" lang=\"" + strLang + "\" xml:lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
            sb.Append("<title>");
            sb.Append(h(strName + " - " + KPRes.EmergencySheet));
            sb.AppendLine("</title>");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            string strFont = "\"Arial\", \"Tahoma\", \"Verdana\", sans-serif;";

            // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
            if (Program.Translation.IsFor("fa"))
            {
                strFont = "\"Tahoma\", \"Arial\", \"Verdana\", sans-serif;";
            }

            sb.AppendLine("body, p, div, h1, h2, h3, h4, h5, h6, ol, ul, li, td, th, dd, dt, a {");
            sb.AppendLine("\tfont-family: " + strFont);
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("body, p, div, table {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("}");

            sb.AppendLine("p, h3 {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tfont-size: 2em;");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tfont-size: 1.5em;");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h3 {");
            sb.AppendLine("\tfont-size: 1.2em;");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            sb.AppendLine("}");
            sb.AppendLine("h4 { font-size: 1em; }");
            sb.AppendLine("h5 { font-size: 0.89em; }");
            sb.AppendLine("h6 { font-size: 0.6em; }");

            sb.AppendLine("a:visited {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:active {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");
            sb.AppendLine("a:link {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover {");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            // Add the temporary content identifier
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\" cellspacing=\"0\" cellpadding=\"0\"><tr>");
            sb.AppendLine("<td style=\"text-align: " + strLogLeft + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(KPRes.EmergencySheet) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: " + strLogRight + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(KPRes.EmergencySheet) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: " + strLogRight + ";\">" +
                          h(TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit    = "<table class=\"fillinline\"><tr><td>";
            const string strFillInitLtr = "<table class=\"fillinline\"><tr><td dir=\"ltr\">";
            const string strFillEnd     = "</td></tr></table>";
            string       strFillSym     = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                          "\" style=\"width: 1.3714em; height: 1em;" +
                                          (bRtl ? " transform: scaleX(-1);" : string.Empty) +
                                          "\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             "</td><td style=\"text-align: " + strLogRight + ";\">" +
                             strFillSym + strFillEnd;

            string strFillInitEx = (bRtl ? strFillInitLtr : strFillInit);

            IOConnectionInfo ioc = pd.IOConnectionInfo;

            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(ioc.Path))) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(kf.Path))) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInitEx);
                        try
                        {
                            sb.Append(ne(h(ltrPath(Environment.UserDomainName +
                                                   "\\" + Environment.UserName))));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(c.Name))) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");

            sb.AppendLine("</body></html>");
            return(sb.ToString());
        }
示例#14
0
        private static void ReadEntry(XmlNode xmlNode, PwGroup pgParent,
                                      PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);

            pgParent.AddEntry(pe, true);

            string strAttachDesc = null, strAttachment = null;

            foreach (XmlNode xmlChild in xmlNode)
            {
                if (xmlChild.Name == ElemTitle)
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUserName)
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemUrl)
                {
                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUrl,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemPassword)
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword,
                                       XmlUtil.SafeInnerText(xmlChild)));
                }
                else if (xmlChild.Name == ElemNotes)
                {
                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectNotes,
                                       FilterSpecial(XmlUtil.SafeInnerXml(xmlChild))));
                }
                else if (xmlChild.Name == ElemIcon)
                {
                    pe.IconId = ReadIcon(xmlChild, pe.IconId);
                }
                else if (xmlChild.Name == ElemCreationTime)
                {
                    pe.CreationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastModTime)
                {
                    pe.LastModificationTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemLastAccessTime)
                {
                    pe.LastAccessTime = ParseTime(XmlUtil.SafeInnerText(xmlChild));
                }
                else if (xmlChild.Name == ElemExpiryTime)
                {
                    string strDate = XmlUtil.SafeInnerText(xmlChild);
                    pe.Expires = (strDate != ValueNever);
                    if (pe.Expires)
                    {
                        pe.ExpiryTime = ParseTime(strDate);
                    }
                }
                else if (xmlChild.Name == ElemAttachDesc)
                {
                    strAttachDesc = XmlUtil.SafeInnerText(xmlChild);
                }
                else if (xmlChild.Name == ElemAttachment)
                {
                    strAttachment = XmlUtil.SafeInnerText(xmlChild);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if (!string.IsNullOrEmpty(strAttachDesc) && (strAttachment != null))
            {
                byte[]          pbData = Convert.FromBase64String(strAttachment);
                ProtectedBinary pb     = new ProtectedBinary(false, pbData);
                pe.Binaries.Set(strAttachDesc, pb);
            }
        }
示例#15
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default, true);
            string       strData = sr.ReadToEnd();

            sr.Close();

            CsvOptions o = new CsvOptions();

            o.BackslashIsEscape = false;

            CsvStreamReaderEx csv = new CsvStreamReaderEx(strData, o);

            SortedDictionary <string, PwGroup> dictGroups =
                new SortedDictionary <string, PwGroup>();

            while (true)
            {
                string[] vLine = csv.ReadLine();
                if (vLine == null)
                {
                    break;
                }
                if (vLine.Length == 0)
                {
                    continue;
                }

                if (vLine.Length == 1)
                {
                    Debug.Assert(vLine[0] == StrHeader);
                    continue;
                }

                // Support old version 3.4
                if (vLine.Length == 9)
                {
                    string[] v = new string[13];
                    for (int i = 0; i < 7; ++i)
                    {
                        v[i] = vLine[i];
                    }
                    for (int i = 7; i < 11; ++i)
                    {
                        v[i] = string.Empty;
                    }
                    v[11] = vLine[7];
                    v[12] = vLine[8];

                    vLine = v;
                }

                if (vLine.Length == 13)
                {
                    ProcessCsvLine(vLine, pwStorage, dictGroups);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
示例#16
0
        private static int OTPAuthFormatCorrection(PwDatabase db)
        {
            //Get DB to work on
            PwDatabase otpdb = db;

            OTPDAO.OTPHandler_DB h = GetOTPHandler(db);
            if (h != null)
            {
                if (!h.EnsureOTPUsagePossible(null))
                {
                    return(-1);
                }
                otpdb = h.OTPDB;
            }
            int i = 0;

            foreach (PwEntry pe in otpdb.RootGroup.GetEntries(true).Where(x => x.Strings.Exists(Config.OTPFIELD)))
            {
                //Don't compare strings because strings are not protected and will remain in memory
                char[] ps = pe.Strings.Get(Config.OTPFIELD).ReadChars();
                try
                {
                    if (ps.Length < 15)
                    {
                        continue;
                    }
                    bool bConvert = false;
                    foreach (char[] check in lOTPAuthStart)
                    {
                        if (check.Length > ps.Length)
                        {
                            continue;
                        }
                        bConvert = true;
                        for (int j = 0; j < check.Length; j++)
                        {
                            if (Char.ToLowerInvariant(check[j]) != Char.ToLowerInvariant(ps[j]))
                            {
                                bConvert = false;
                                break;
                            }
                        }
                        if (bConvert)
                        {
                            break;
                        }
                    }
                    if (!bConvert)
                    {
                        break;
                    }
                    KPOTP otp = OTPDAO.GetOTP(pe);
                    if (!otp.Valid)
                    {
                        continue;
                    }
                    i++;
                    pe.CreateBackup(otpdb);
                    pe.Strings.Set(Config.OTPFIELD, otp.OTPAuthString);
                }
                finally { MemUtil.ZeroArray(ps); }
            }
            return(i);
        }
示例#17
0
 public Kdb4File(PwDatabase pwDatabase)
 {
     this.pwDatabase = pwDatabase;
 }
示例#18
0
        public static void MigrateToCustomdata(PwDatabase db, PwEntry pe)
        {
            bool bPreload = !pe.Strings.Exists(Config.DBPreload) || StrUtil.StringToBool(pe.Strings.ReadSafe(Config.DBPreload));

            db.CustomData.Set(Config.DBPreload, StrUtil.BoolToString(bPreload));

            bool bUseDB = !pe.Strings.Exists(Config.DBUsage) || StrUtil.StringToBool(pe.Strings.ReadSafe(Config.DBUsage));

            db.CustomData.Set(Config.DBUsage, StrUtil.BoolToString(bUseDB));

            db.CustomData.Remove(Config.DBKeySources);
            string k = pe.Strings.ReadSafe("KPOTP.KeySources");

            if (!string.IsNullOrEmpty(k))
            {
                db.CustomData.Set(Config.DBKeySources, k);
            }

            if (pe.Binaries.Get(OTPDAO.OTPHandler_DB.DBNAME + ".kdbx") != null)
            {
                ProtectedBinary pbOTPDB = pe.Binaries.Get(OTPDAO.OTPHandler_DB.DBNAME + ".kdbx");
                string          otpdb   = OTPDAO.OTPHandler_DB.ConvertToCustomData(pbOTPDB.ReadData());
                db.CustomData.Set(OTPDAO.OTPHandler_DB.DBNAME, otpdb);
            }

            bool bDeleted = false;

            if (db.RecycleBinEnabled)
            {
                PwGroup pgRecycleBin = db.RootGroup.FindGroup(db.RecycleBinUuid, true);
                if (pgRecycleBin == null)
                {
                    MethodInfo miEnsureRecycleBin = Program.MainForm.GetType().GetMethod("EnsureRecycleBin", BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                    if (miEnsureRecycleBin != null)
                    {
                        object[] p = new object[] { null, db, null };
                        try
                        {
                            miEnsureRecycleBin.Invoke(null, p);
                            pgRecycleBin = p[0] as PwGroup;
                        }
                        catch { }
                    }
                }
                if (pgRecycleBin != null)
                {
                    pe.ParentGroup.Entries.Remove(pe);
                    pgRecycleBin.AddEntry(pe, true);
                    bDeleted = true;
                }
            }
            else if (!db.RecycleBinEnabled && !bUseDB)
            {
                pe.ParentGroup.Entries.Remove(pe);
                bDeleted = true;
            }
            if (!bDeleted)
            {
                pe.Strings.Remove(Config.DBPreload);
                pe.Strings.Remove(Config.DBUsage);
                pe.Strings.Remove(Config.DBKeySources);
                pe.Binaries.Remove(OTPDAO.OTPHandler_DB.DBNAME + ".kdbx");
                pe.Touch(true);
            }

            db.Modified        = true;
            db.SettingsChanged = DateTime.UtcNow;
            System.Threading.Thread tUpdate = new System.Threading.Thread(UpdateUI);
            tUpdate.Start(new object[] { bDeleted, db });
            OTPDAO.InitEntries(db);
            OTPDAO.RemoveHandler(db.IOConnectionInfo.Path, true);
        }
示例#19
0
文件: KdbxFile.cs 项目: saadware/kpn
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="pwDataStore">The <c>PwDatabase</c> instance that the
        /// class will load file data into or use to create a KDBX file.</param>
        public KdbxFile(PwDatabase pwDataStore)
        {
            Debug.Assert(pwDataStore != null);
            if(pwDataStore == null) throw new ArgumentNullException("pwDataStore");

            m_pwDatabase = pwDataStore;
        }
示例#20
0
        private static int CheckOTPDataMigration(PwDatabase db)
        {
            const string SEED     = "KeePassOTP.Seed";
            const string SETTINGS = "KeePassOTP.Settings";

            //Get DB to work on
            PwDatabase otpdb = db;

            OTPDAO.OTPHandler_DB h = GetOTPHandler(db);
            if (h != null)
            {
                if (!h.EnsureOTPUsagePossible(null))
                {
                    return(-1);
                }
                otpdb = h.OTPDB;
            }

            List <PwEntry> lEntries = otpdb.RootGroup.GetEntries(true).Where(x => x.Strings.Exists(SEED) && x.Strings.Exists(SETTINGS)).ToList();

            int migrated = 0;

            foreach (PwEntry pe in lEntries)
            {
                ProtectedString seed     = pe.Strings.Get(SEED);
                string          settings = pe.Strings.ReadSafe(SETTINGS);

                string title = pe.Strings.ReadSafe(PwDefs.TitleField);
                string user  = pe.Strings.ReadSafe(PwDefs.UserNameField);
                if (string.IsNullOrEmpty(title))
                {
                    title = PluginTranslation.PluginTranslate.PluginName;
                }
                if (!string.IsNullOrEmpty(user))
                {
                    user = "******" + user;
                }

                KPOTP otp = ConvertOTPSettings(settings);
                otp.OTPSeed = seed;

                otp.Issuer = title;
                otp.Label  = user;
                ProtectedString result = otp.OTPAuthString;

                pe.CreateBackup(db);
                pe.Strings.Remove(SEED);
                pe.Strings.Remove(SETTINGS);
                pe.Strings.Set(Config.OTPFIELD, result);
                if (h == null)
                {
                    pe.Touch(true);
                }
                migrated++;
            }
            if (migrated > 0)
            {
                db.Modified = true;
                if (h == null)
                {
                    Program.MainForm.UpdateUI(false, null, false, null, false, null, db == Program.MainForm.ActiveDatabase);
                }
            }
            return(migrated);
        }
示例#21
0
        private static void CreateEntry(PwEntry peTemplate)
        {
            if (peTemplate == null)
            {
                Debug.Assert(false); return;
            }

            PwDatabase pd = Program.MainForm.ActiveDatabase;

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

            PwGroup pgContainer = Program.MainForm.GetSelectedGroup();

            if (pgContainer == null)
            {
                pgContainer = pd.RootGroup;
            }

            PwEntry pe = peTemplate.Duplicate();

            pe.History.Clear();

            if (EntryTemplates.EntryCreating != null)
            {
                EntryTemplates.EntryCreating(null, new TemplateEntryEventArgs(
                                                 peTemplate.CloneDeep(), pe));
            }

            PwEntryForm pef = new PwEntryForm();

            pef.InitEx(pe, PwEditMode.AddNewEntry, pd, Program.MainForm.ClientIcons,
                       false, true);

            if (UIUtil.ShowDialogAndDestroy(pef) == DialogResult.OK)
            {
                pgContainer.AddEntry(pe, true, true);

                MainForm mf = Program.MainForm;
                if (mf != null)
                {
                    mf.UpdateUI(false, null, pd.UINeedsIconUpdate, null,
                                true, null, true);

                    PwObjectList <PwEntry> vSelect = new PwObjectList <PwEntry>();
                    vSelect.Add(pe);
                    mf.SelectEntries(vSelect, true, true);

                    mf.EnsureVisibleEntry(pe.Uuid);
                    mf.UpdateUI(false, null, false, null, false, null, false);

                    if (Program.Config.Application.AutoSaveAfterEntryEdit)
                    {
                        mf.SaveDatabase(pd, null);
                    }
                }
                else
                {
                    Debug.Assert(false);
                }

                if (EntryTemplates.EntryCreated != null)
                {
                    EntryTemplates.EntryCreated(null, new TemplateEntryEventArgs(
                                                    peTemplate.CloneDeep(), pe));
                }
            }
            else
            {
                Program.MainForm.UpdateUI(false, null, pd.UINeedsIconUpdate, null,
                                          pd.UINeedsIconUpdate, null, false);
            }
        }
示例#22
0
        private static void AddEntry(string[] vLine, PwDatabase pd)
        {
            int n = vLine.Length;

            if (n == 0)
            {
                return;
            }

            PwEntry pe = new PwEntry(true, true);

            pd.RootGroup.AddEntry(pe, true);

            string[] vFields = null;
            if (n == 2)
            {
                vFields = new string[2] {
                    PwDefs.TitleField, PwDefs.UrlField
                }
            }
            ;
            else if (n == 3)
            {
                vFields = new string[3] {
                    PwDefs.TitleField, PwDefs.UrlField,
                    PwDefs.UserNameField
                }
            }
            ;
            else if (n == 4)
            {
                if ((vLine[2].Length == 0) && (vLine[3].Length == 0))
                {
                    vFields = new string[4] {
                        PwDefs.TitleField, PwDefs.UserNameField,
                        PwDefs.NotesField, PwDefs.NotesField
                    }
                }
                ;
                else
                {
                    vFields = new string[4] {
                        PwDefs.TitleField, PwDefs.NotesField,
                        PwDefs.UserNameField, PwDefs.NotesField
                    }
                };
            }
            else if (n == 5)
            {
                vFields = new string[5] {
                    PwDefs.TitleField, PwDefs.UrlField,
                    PwDefs.UserNameField, PwDefs.PasswordField, PwDefs.NotesField
                }
            }
            ;
            else if (n == 6)
            {
                vFields = new string[6] {
                    PwDefs.TitleField, PwDefs.UrlField,
                    PwDefs.UserNameField, PwDefs.UserNameField, PwDefs.PasswordField,
                    PwDefs.NotesField
                }
            }
            ;
            else if (n == 7)
            {
                vFields = new string[7] {
                    PwDefs.TitleField, PwDefs.UserNameField,
                    PwDefs.NotesField, PwDefs.NotesField, PwDefs.NotesField,
                    PwDefs.NotesField, PwDefs.NotesField
                }
            }
            ;

            if (m_rxIsDate == null)
            {
                m_rxIsDate = new Regex(@"^\d{4}-\d+-\d+$");
                m_rxIsGuid = new Regex(
                    @"^\{[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}$");
            }

            if ((vLine[0].Length == 0) && (n >= 2) && m_rxIsDate.IsMatch(vLine[1]))
            {
                vFields = null;

                vLine[0] = KPRes.Id;
                for (int i = 1; i < n; ++i)
                {
                    string strPart = vLine[i];
                    if (strPart.Equals("NO_TYPE", StrUtil.CaseIgnoreCmp) ||
                        m_rxIsGuid.IsMatch(strPart))
                    {
                        vLine[i] = string.Empty;
                    }
                }
            }

            for (int i = 0; i < n; ++i)
            {
                string str = vLine[i];
                if (str.Length == 0)
                {
                    continue;
                }
                if (str.Equals("dashlaneappcredential", StrUtil.CaseIgnoreCmp))
                {
                    continue;
                }

                string strField = ((vFields != null) ? vFields[i] : null);
                if (strField == null)
                {
                    if (i == 0)
                    {
                        strField = PwDefs.TitleField;
                    }
                    else
                    {
                        strField = PwDefs.NotesField;
                    }
                }

                if ((strField == PwDefs.UrlField) && (str.IndexOf('.') >= 0))
                {
                    str = ImportUtil.FixUrl(str);
                }

                ImportUtil.AppendToField(pe, strField, str, pd);
            }
        }
    }
示例#23
0
        /// <summary>
        /// Retrieves a OneDrive Refresh Token from the provided KeePass database
        /// </summary>
        /// <param name="keePassDatabase">KeePass database instance to get the Refresh Token from</param>
        /// <returns>OneDrive Refresh Token if available or NULL if no Refresh Token found for the provided database</returns>
        public static string GetRefreshTokenFromKeePassDatabase(PwDatabase keePassDatabase)
        {
            var refreshToken = keePassDatabase.CustomData.Get("KoenZomers.KeePass.OneDriveSync.RefreshToken");

            return(refreshToken);
        }
示例#24
0
 public void InitEx(PwGroup pg, ImageList ilClientIcons, PwDatabase pwDatabase)
 {
     InitEx(pg, false, ilClientIcons, pwDatabase);
 }
示例#25
0
 public void Initialise(PwDatabase pwStorage)
 {
     KeePassHelper.InitialiseGroupComboBox(this.comboBoxGroup, pwStorage);
 }
示例#26
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="bResult">See <c>Result</c> property.</param>
 public FileSavedEventArgs(bool bSuccess, PwDatabase pwDatabase, Guid eventGuid)
 {
     m_bResult    = bSuccess;
     m_pwDatabase = pwDatabase;
     m_eventGuid  = eventGuid;
 }
示例#27
0
 private static Image GetCustomIcon(PwDatabase database, PwUuid customIconId)
 {
     return(database.GetCustomIcon(customIconId, DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16)));
 }
示例#28
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public FileCreatedEventArgs(PwDatabase pwDatabase)
 {
     m_pwDatabase = pwDatabase;
 }
示例#29
0
        private static void ImportIntoCurrentDatabase(EcasAction a, EcasContext ctx)
        {
            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);

            if (string.IsNullOrEmpty(strPath))
            {
                return;
            }
            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strPath);

            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            FileFormatProvider ff = Program.FileFormatPool.Find(strFormat);

            if (ff == null)
            {
                throw new Exception(KPRes.Unknown + ": " + strFormat);
            }

            uint          uMethod = EcasUtil.GetParamUInt(a.Parameters, 2);
            Type          tMM     = Enum.GetUnderlyingType(typeof(PwMergeMethod));
            object        oMethod = Convert.ChangeType(uMethod, tMM);
            PwMergeMethod mm      = PwMergeMethod.None;

            if (Enum.IsDefined(typeof(PwMergeMethod), oMethod))
            {
                mm = (PwMergeMethod)oMethod;
            }
            else
            {
                Debug.Assert(false);
            }
            if (mm == PwMergeMethod.None)
            {
                mm = PwMergeMethod.CreateNewUuids;
            }

            CompositeKey cmpKey = KeyFromParams(a, 3, 4, 5);

            if ((cmpKey == null) && ff.RequiresKey)
            {
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc, false, true);

                if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                {
                    return;
                }

                cmpKey = kpf.CompositeKey;
                UIUtil.DestroyForm(kpf);
            }

            bool?b = true;

            try { b = ImportUtil.Import(pd, ff, ioc, mm, cmpKey); }
            finally
            {
                if (b.GetValueOrDefault(false))
                {
                    Program.MainForm.UpdateUI(false, null, true, null, true, null, true);
                }
            }
        }
示例#30
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public FileOpenedEventArgs(PwDatabase pwDatabase)
 {
     m_pwDatabase = pwDatabase;
 }
示例#31
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();
            sInput.Close();

            Dictionary <string, PwGroup> dGroups = new Dictionary <string, PwGroup>();

            dGroups[string.Empty] = pwStorage.RootGroup;

            CsvOptions opt = new CsvOptions();

            opt.BackslashIsEscape = false;

            CsvStreamReaderEx csv = new CsvStreamReaderEx(strData, opt);

            while (true)
            {
                string[] v = csv.ReadLine();
                if (v == null)
                {
                    break;
                }
                if (v.Length == 0)
                {
                    continue;
                }
                if (v[0].StartsWith("TurboPasswords CSV Export File"))
                {
                    continue;
                }
                if (v.Length < 24)
                {
                    Debug.Assert(false); continue;
                }
                if ((v[0] == "Category") && (v[1] == "Type"))
                {
                    continue;
                }

                PwEntry pe = new PwEntry(true, true);

                PwGroup pg;
                string  strGroup = v[0];
                if (!dGroups.TryGetValue(strGroup, out pg))
                {
                    pg = new PwGroup(true, true, strGroup, PwIcon.Folder);
                    dGroups[string.Empty].AddGroup(pg, true);
                    dGroups[strGroup] = pg;
                }
                pg.AddEntry(pe, true);

                string strType = v[1];

                for (int f = 0; f < 6; ++f)
                {
                    string strKey   = v[2 + (2 * f)];
                    string strValue = v[2 + (2 * f) + 1];
                    if (strKey.Length == 0)
                    {
                        strKey = PwDefs.NotesField;
                    }
                    if (strValue.Length == 0)
                    {
                        continue;
                    }

                    if (strKey == "Description")
                    {
                        strKey = PwDefs.TitleField;
                    }
                    else if (((strType == "Contact") || (strType == "Personal Info")) &&
                             (strKey == "Name"))
                    {
                        strKey = PwDefs.TitleField;
                    }
                    else if (((strType == "Membership") || (strType == "Insurance")) &&
                             (strKey == "Company"))
                    {
                        strKey = PwDefs.TitleField;
                    }
                    else if (strKey == "SSN")
                    {
                        strKey = PwDefs.UserNameField;
                    }
                    else
                    {
                        string strMapped = ImportUtil.MapNameToStandardField(strKey, false);
                        if (!string.IsNullOrEmpty(strMapped))
                        {
                            strKey = strMapped;
                        }
                    }

                    ImportUtil.AppendToField(pe, strKey, strValue, pwStorage);
                }

                ImportUtil.AppendToField(pe, PwDefs.NotesField, v[20], pwStorage,
                                         "\r\n\r\n", false);
                if (v[21].Length > 0)
                {
                    ImportUtil.AppendToField(pe, "Login URL", v[21], pwStorage, null, true);
                }
            }
        }
示例#32
0
 public SprContext(PwEntry pe, PwDatabase pd, SprCompileFlags fl)
 {
     Init(pe, pd, false, false, fl);
 }
示例#33
0
        private static void ProcessCsvLine(string[] vLine, PwDatabase pwStorage,
                                           SortedDictionary <string, PwGroup> dictGroups)
        {
            string strType = ParseCsvWord(vLine[0]);

            string strGroupName = ParseCsvWord(vLine[12]);             // + " - " + strType;

            if (strGroupName.Length == 0)
            {
                strGroupName = strType;
            }

            SplashIdMapping mp = null;

            foreach (SplashIdMapping mpFind in SplashIdCsv402.SplashIdMappings)
            {
                if (mpFind.TypeName == strType)
                {
                    mp = mpFind;
                    break;
                }
            }

            PwIcon pwIcon = ((mp != null) ? mp.Icon : PwIcon.Key);

            PwGroup pg = null;

            if (dictGroups.ContainsKey(strGroupName))
            {
                pg = dictGroups[strGroupName];
            }
            else
            {
                // PwIcon pwGroupIcon = ((pwIcon == PwIcon.Key) ?
                //	PwIcon.FolderOpen : pwIcon);
                // pg = new PwGroup(true, true, strGroupName, pwGroupIcon);

                pg      = new PwGroup(true, true);
                pg.Name = strGroupName;

                pwStorage.RootGroup.AddGroup(pg, true);
                dictGroups[strGroupName] = pg;
            }

            PwEntry pe = new PwEntry(true, true);

            pg.AddEntry(pe, true);

            pe.IconId = pwIcon;

            List <string> vTags = StrUtil.StringToTags(strType);

            foreach (string strTag in vTags)
            {
                pe.AddTag(strTag);
            }

            for (int iField = 0; iField < 9; ++iField)
            {
                string strData = ParseCsvWord(vLine[iField + 1]);
                if (strData.Length == 0)
                {
                    continue;
                }

                string strLookup = ((mp != null) ? mp.FieldNames[iField] :
                                    null);
                string strField = (strLookup ?? ("Field " + (iField + 1).ToString()));

                ImportUtil.AppendToField(pe, strField, strData, pwStorage);
            }

            ImportUtil.AppendToField(pe, PwDefs.NotesField, ParseCsvWord(vLine[11]),
                                     pwStorage);

            DateTime?odt = TimeUtil.ParseUSTextDate(ParseCsvWord(vLine[10]),
                                                    DateTimeKind.Local);

            if (odt.HasValue)
            {
                DateTime dt = TimeUtil.ToUtc(odt.Value, false);
                pe.LastAccessTime       = dt;
                pe.LastModificationTime = dt;
            }
        }
示例#34
0
 public SprContext(PwEntry pe, PwDatabase pd, SprCompileFlags fl,
                   bool bEncodeAsAutoTypeSequence, bool bEncodeForCommandLine)
 {
     Init(pe, pd, bEncodeAsAutoTypeSequence, bEncodeForCommandLine, fl);
 }
示例#35
0
		public static bool WriteEntries(Stream msOutput, PwDatabase pdContext,
			PwEntry[] vEntries)
		{
			if(msOutput == null) { Debug.Assert(false); return false; }
			// pdContext may be null
			if(vEntries == null) { Debug.Assert(false); return false; }

			/* KdbxFile f = new KdbxFile(pwDatabase);
			f.m_format = KdbxFormat.PlainXml;

			XmlTextWriter xtw = null;
			try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); }
			catch(Exception) { Debug.Assert(false); return false; }
			if(xtw == null) { Debug.Assert(false); return false; }

			f.m_xmlWriter = xtw;

			xtw.Formatting = Formatting.Indented;
			xtw.IndentChar = '\t';
			xtw.Indentation = 1;

			xtw.WriteStartDocument(true);
			xtw.WriteStartElement(ElemRoot);

			foreach(PwEntry pe in vEntries)
				f.WriteEntry(pe, false);

			xtw.WriteEndElement();
			xtw.WriteEndDocument();

			xtw.Flush();
			xtw.Close();
			return true; */

			PwDatabase pd = new PwDatabase();
			pd.New(new IOConnectionInfo(), new CompositeKey());

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

			foreach(PwEntry pe in vEntries)
			{
				PwUuid pu = pe.CustomIconUuid;
				if(!pu.Equals(PwUuid.Zero) && (pd.GetCustomIconIndex(pu) < 0))
				{
					int i = -1;
					if(pdContext != null) i = pdContext.GetCustomIconIndex(pu);
					if(i >= 0)
					{
						PwCustomIcon ci = pdContext.CustomIcons[i];
						pd.CustomIcons.Add(ci);
					}
					else { Debug.Assert(pdContext == null); }
				}

				PwEntry peCopy = pe.CloneDeep();
				pg.AddEntry(peCopy, true);
			}

			KdbxFile f = new KdbxFile(pd);
			f.Save(msOutput, null, KdbxFormat.PlainXml, null);
			return true;
		}
示例#36
0
 public YandexDiscSyncConf(PwDatabase pwDatabase)
 {
     _pwDatabase = pwDatabase;
     ReadFromPwDatabase();
 }
示例#37
0
        /// <summary>
        /// Write entries to a stream.
        /// </summary>
        /// <param name="msOutput">Output stream to which the entries will be written.</param>
        /// <param name="vEntries">Entries to serialize.</param>
        /// <returns>Returns <c>true</c>, if the entries were written successfully
        /// to the stream.</returns>
        public static bool WriteEntries(Stream msOutput, PwEntry[] vEntries)
        {
            /* KdbxFile f = new KdbxFile(pwDatabase);
            f.m_format = KdbxFormat.PlainXml;

            XmlTextWriter xtw = null;
            try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); }
            catch(Exception) { Debug.Assert(false); return false; }
            if(xtw == null) { Debug.Assert(false); return false; }

            f.m_xmlWriter = xtw;

            xtw.Formatting = Formatting.Indented;
            xtw.IndentChar = '\t';
            xtw.Indentation = 1;

            xtw.WriteStartDocument(true);
            xtw.WriteStartElement(ElemRoot);

            foreach(PwEntry pe in vEntries)
                f.WriteEntry(pe, false);

            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Flush();
            xtw.Close();
            return true; */

            PwDatabase pd = new PwDatabase();
            pd.New(new IOConnectionInfo(), new CompositeKey());

            foreach(PwEntry peCopy in vEntries)
                pd.RootGroup.AddEntry(peCopy.CloneDeep(), true);

            KdbxFile f = new KdbxFile(pd);
            f.Save(msOutput, null, KdbxFormat.PlainXml, null);
            return true;
        }
示例#38
0
 public void ChangeDatabase(PwDatabase db)
 {
     _pwDatabase = db;
 }
示例#39
0
 public static List<PwEntry> ReadEntries(PwDatabase pwDatabase, Stream msData)
 {
     return ReadEntries(msData);
 }
示例#40
0
		public static List<PwEntry> ReadEntries(PwDatabase pdContext, Stream msData)
		{
			return ReadEntries(msData, pdContext, true);
		}