Ejemplo n.º 1
0
		private static void ProcessCsvLine(string strLine, PwDatabase pwStorage)
		{
			List<string> list = ImportUtil.SplitCsvLine(strLine, ",");
			Debug.Assert(list.Count == 5);

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

			if(list.Count == 5)
			{
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectTitle,
					ProcessCsvWord(list[0])));
				pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUserName,
					ProcessCsvWord(list[1])));
				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectPassword,
					ProcessCsvWord(list[2])));
				pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUrl,
					ProcessCsvWord(list[3])));
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes,
					ProcessCsvWord(list[4])));
			}
			else throw new FormatException("Invalid field count!");
		}
Ejemplo n.º 2
0
		private static void AddItem(PwEntry pe)
		{
			if(pe == null) { Debug.Assert(false); return; }

			string strText = StrUtil.EncodeMenuText(pe.Strings.ReadSafe(
				PwDefs.TitleField));
			ToolStripMenuItem tsmi = new ToolStripMenuItem(strText);
			tsmi.Tag = pe;
			tsmi.Click += OnMenuExecute;

			Image img = null;
			PwDatabase pd = Program.MainForm.DocumentManager.SafeFindContainerOf(pe);
			if(pd != null)
			{
				if(!pe.CustomIconUuid.Equals(PwUuid.Zero))
					img = DpiUtil.GetIcon(pd, pe.CustomIconUuid);
				if(img == null)
				{
					try { img = Program.MainForm.ClientIcons.Images[(int)pe.IconId]; }
					catch(Exception) { Debug.Assert(false); }
				}
			}
			if(img == null) img = Properties.Resources.B16x16_KGPG_Key1;
			tsmi.Image = img;

			m_btnItemsHost.DropDownItems.Add(tsmi);
			m_vToolStripItems.Add(tsmi);
		}
Ejemplo n.º 3
0
        public static string FillPlaceholders(string strText, PwEntry pe,
            SprContentFlags cf)
        {
            if(pe == null) return strText;

            string str = strText;

            if(str.ToUpper().IndexOf(@"{PICKPASSWORDCHARS}") >= 0)
            {
                ProtectedString ps = pe.Strings.Get(PwDefs.PasswordField);
                if(ps != null)
                {
                    byte[] pb = ps.ReadUtf8();
                    bool bNotEmpty = (pb.Length > 0);
                    Array.Clear(pb, 0, pb.Length);

                    if(bNotEmpty)
                    {
                        CharPickerForm cpf = new CharPickerForm();
                        cpf.InitEx(ps, true, true);

                        if(cpf.ShowDialog() == DialogResult.OK)
                        {
                            str = StrUtil.ReplaceCaseInsensitive(str, @"{PICKPASSWORDCHARS}",
                                SprEngine.TransformContent(cpf.SelectedCharacters.ReadString(), cf));
                        }
                    }
                }

                str = StrUtil.ReplaceCaseInsensitive(str, @"{PICKPASSWORDCHARS}", string.Empty);
            }

            return str;
        }
Ejemplo n.º 4
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			Debug.Assert(psToCopy != null);
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");

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

			string strData = SprEngine.Compile(psToCopy.ReadString(), false,
				peEntryInfo, pwReferenceSource, false, false);

			try
			{
				ClipboardUtil.Clear();

				DataObject doData = CreateProtectedDataObject(strData);
				Clipboard.SetDataObject(doData);

				m_pbDataHash32 = HashClipboard();
				m_strFormat = null;

				RaiseCopyEvent(bIsEntryInfo, strData);
			}
			catch(Exception) { Debug.Assert(false); return false; }

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

			// SprEngine.Compile might have modified the database
			Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

			return true;
		}
Ejemplo n.º 5
0
                public void SetEntry(PwEntry e)
                {
                    KpDatabase = new PwDatabase();
                    KpDatabase.New(new IOConnectionInfo(), new CompositeKey());

                    KpDatabase.RootGroup.AddEntry(e, true);
                }
Ejemplo n.º 6
0
        private static void AddItem(PwEntry pe)
        {
            if(pe == null) { Debug.Assert(false); return; }

            ToolStripMenuItem tsmi = new ToolStripMenuItem(pe.Strings.ReadSafe(
                PwDefs.TitleField));
            tsmi.Tag = pe;
            tsmi.Click += OnMenuExecute;

            Image img = null;
            PwDatabase pd = Program.MainForm.ActiveDatabase;
            if(pd != null)
            {
                if(!pe.CustomIconUuid.EqualsValue(PwUuid.Zero))
                    img = pd.GetCustomIcon(pe.CustomIconUuid);
                if(img == null)
                {
                    try { img = Program.MainForm.ClientIcons.Images[(int)pe.IconId]; }
                    catch(Exception) { Debug.Assert(false); }
                }
            }
            if(img == null) img = Properties.Resources.B16x16_KGPG_Key1;
            tsmi.Image = img;

            m_btnItemsHost.DropDownItems.Add(tsmi);
            m_vToolStripItems.Add(tsmi);
        }
Ejemplo n.º 7
0
        private PwEntryView(GroupBaseActivity groupActivity, PwEntry pw, int pos)
            : base(groupActivity)
        {
            _groupActivity = groupActivity;

            View ev = Inflate(groupActivity, Resource.Layout.entry_list_entry, null);
            _textView = (TextView)ev.FindViewById(Resource.Id.entry_text);
            _textView.TextSize = PrefsUtil.GetListTextSize(groupActivity);

            _textviewDetails = (TextView)ev.FindViewById(Resource.Id.entry_text_detail);
            _textviewDetails.TextSize = PrefsUtil.GetListDetailTextSize(groupActivity);

            _textgroupFullPath = (TextView)ev.FindViewById(Resource.Id.group_detail);
            _textgroupFullPath.TextSize = PrefsUtil.GetListDetailTextSize(groupActivity);

            _showDetail = PreferenceManager.GetDefaultSharedPreferences(groupActivity).GetBoolean(
                groupActivity.GetString(Resource.String.ShowUsernameInList_key),
                Resources.GetBoolean(Resource.Boolean.ShowUsernameInList_default));

            _showGroupFullPath = PreferenceManager.GetDefaultSharedPreferences(groupActivity).GetBoolean(
                groupActivity.GetString(Resource.String.ShowGroupnameInSearchResult_key),
                Resources.GetBoolean(Resource.Boolean.ShowGroupnameInSearchResult_default));

            _isSearchResult = _groupActivity is keepass2android.search.SearchResults;

            PopulateView(ev, pw, pos);

            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent);

            AddView(ev, lp);
        }
Ejemplo n.º 8
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");
			return Copy(psToCopy.ReadString(), true, bIsEntryInfo, peEntryInfo,
				pwReferenceSource, IntPtr.Zero);
		}
Ejemplo n.º 9
0
 public DeleteEntry(Context ctx, IKp2aApp app, PwEntry entry, OnFinish finish)
     : base(finish, app)
 {
     Ctx = ctx;
     Db = app.GetDb();
     _entry = entry;
 }
Ejemplo n.º 10
0
        // public bool CopyHistory
        // {
        //    get { return m_bCopyHistory; }
        // }
        public void ApplyTo(PwEntry peNew, PwEntry pe, PwDatabase pd)
        {
            if((peNew == null) || (pe == null)) { Debug.Assert(false); return; }

            Debug.Assert(peNew.Strings.ReadSafe(PwDefs.UserNameField) ==
                pe.Strings.ReadSafe(PwDefs.UserNameField));
            Debug.Assert(peNew.Strings.ReadSafe(PwDefs.PasswordField) ==
                pe.Strings.ReadSafe(PwDefs.PasswordField));

            if(m_bAppendCopy && (pd != null))
            {
                string strTitle = peNew.Strings.ReadSafe(PwDefs.TitleField);
                peNew.Strings.Set(PwDefs.TitleField, new ProtectedString(
                    pd.MemoryProtection.ProtectTitle, strTitle + " - " +
                    KPRes.CopyOfItem));
            }

            if(m_bFieldRefs && (pd != null))
            {
                string strUser = @"{REF:U@I:" + pe.Uuid.ToHexString() + @"}";
                peNew.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                    pd.MemoryProtection.ProtectUserName, strUser));

                string strPw = @"{REF:P@I:" + pe.Uuid.ToHexString() + @"}";
                peNew.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                    pd.MemoryProtection.ProtectPassword, strPw));
            }

            if(!m_bCopyHistory)
                peNew.History = new PwObjectList<PwEntry>();
        }
Ejemplo n.º 11
0
        public static bool Copy(string strToCopy, bool bIsEntryInfo,
            PwEntry peEntryInfo, PwDatabase pwReferenceSource)
        {
            Debug.Assert(strToCopy != null);
            if(strToCopy == null) throw new ArgumentNullException("strToCopy");

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

            string strData = SprEngine.Compile(strToCopy, false, peEntryInfo,
                pwReferenceSource, false, false);

            try
            {
                Clipboard.Clear();

                DataObject doData = CreateProtectedDataObject(strData);
                Clipboard.SetDataObject(doData);

                m_pbDataHash32 = HashClipboard();
                m_strFormat = null;
            }
            catch(Exception) { Debug.Assert(false); return false; }

            return true;
        }
Ejemplo n.º 12
0
 public AfterUpdate(PwEntry backup, PwEntry updatedEntry, IKp2aApp app, OnFinish finish)
     : base(finish)
 {
     _backup = backup;
     _updatedEntry = updatedEntry;
     _app = app;
 }
Ejemplo n.º 13
0
            /// <summary>
            /// Tells KeePass what to display in the column.
            /// </summary>
            /// <param name="strColumnName"></param>
            /// <param name="pe"></param>
            /// <returns>String displayed in the columns.</returns>
            public override string GetCellData(string strColumnName, PwEntry pe)
            {
                if (strColumnName == null) throw new ArgumentNullException("strColumnName");
                if (pe == null) throw new ArgumentNullException("pe");
                if (plugin.SettingsCheck(pe) && plugin.SeedCheck(pe))
                {
                    bool ValidInterval;
                    bool ValidLength;
                    bool ValidUrl;
                    if (plugin.SettingsValidate(pe, out ValidInterval, out ValidLength, out ValidUrl))
                    {
                        string[] Settings = plugin.SettingsGet(pe);

                        TOTPProvider TOTPGenerator = new TOTPProvider(Settings, ref plugin.TimeCorrections);

                        if (plugin.SeedValidate(pe))
                        {
                            return TOTPGenerator.GenerateByByte(
                                Base32.Decode(plugin.SeedGet(pe).ReadString().ExtWithoutSpaces())) + (m_host.CustomConfig.GetBool(setname_bool_TOTPColumnTimer_Visible, true) ? TOTPGenerator.Timer.ToString().ExtWithParenthesis().ExtWithSpaceBefore() : string.Empty);
                        }
                        return TrayTOTP_CustomColumn_Localization.strWarningBadSeed;
                    }
                    return TrayTOTP_CustomColumn_Localization.strWarningBadSet;
                }
                return (plugin.SettingsCheck(pe) || plugin.SeedCheck(pe) ? TrayTOTP_CustomColumn_Localization.strWarningStorage : string.Empty);
            }
Ejemplo n.º 14
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;
        }
Ejemplo n.º 15
0
		public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner)
		{
			if(strToCopy == null) throw new ArgumentNullException("strToCopy");

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

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

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

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

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

			m_strFormat = null;

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

			RaiseCopyEvent(bIsEntryInfo, strData);

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

			// SprEngine.Compile might have modified the database
			MainForm mf = Program.MainForm;
			if((mf != null) && bSprCompile)
			{
				mf.RefreshEntriesList();
				mf.UpdateUI(false, null, false, null, false, null, false);
			}

			return true;
		}
Ejemplo n.º 16
0
        public UpdateEntry(Context ctx, IKp2aApp app, PwEntry oldE, PwEntry newE, OnFinish finish)
            : base(finish)
        {
            _ctx = ctx;
            _app = app;

            _onFinishToRun = new AfterUpdate(oldE, newE, app, finish);
        }
Ejemplo n.º 17
0
			public GxiContext ModifyWith(PwEntry pe)
			{
				GxiContext c = (GxiContext)MemberwiseClone();
				Debug.Assert(object.ReferenceEquals(c.m_dStringKeyRepl, m_dStringKeyRepl));

				c.m_pe = pe;
				return c;
			}
 public override string GetCellData(string strColumnName, PwEntry pe)
 {
     if (strColumnName == Properties.Resources.AutoTypeEnabled) {
         return pe.AutoType.Enabled ? KPRes.Yes : KPRes.No;
     } else {
         return string.Empty;
     }
 }
Ejemplo n.º 19
0
        public AutoTypeCtx(string strSequence, PwEntry pe, PwDatabase pd)
        {
            if(strSequence == null) throw new ArgumentNullException("strSequence");

            m_strSeq = strSequence;
            m_pe = pe;
            m_pd = pd;
        }
Ejemplo n.º 20
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);
		}
Ejemplo n.º 21
0
 public static bool hasFields(PwEntry entry)
 {
     foreach (KeyValuePair<string, ProtectedString> kvpStr in entry.Strings)
     {
         if (!PwDefs.IsStandardField(kvpStr.Key)) return true;
     }
     return false;
 }
Ejemplo n.º 22
0
		public PwListItem(PwEntry pe)
		{
			if(pe == null) throw new ArgumentNullException("pe");

			m_pe = pe;

			m_id = m_idNext;
			unchecked { ++m_idNext; }
		}
Ejemplo n.º 23
0
		public AutoTypeEventArgs(string strSequence, bool bObfuscated, PwEntry pe)
		{
			if(strSequence == null) throw new ArgumentNullException("strSequence");
			// pe may be null

			m_strSeq = strSequence;
			this.SendObfuscated = bObfuscated;
			this.Entry = pe;
		}
Ejemplo n.º 24
0
		public static bool Copy(string strToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			Debug.Assert(strToCopy != null);
			if(strToCopy == null) throw new ArgumentNullException("strToCopy");

			return ClipboardUtil.Copy(new ProtectedString(false, strToCopy),
				bIsEntryInfo, peEntryInfo, pwReferenceSource);
		}
        public void PickCustomField(string placeholder, PwEntry entry)
        {
            this.label_PlaceholderInfo.Text = string.Format(this.label_PlaceholderInfo.Text, placeholder);

            foreach (KeyValuePair<string, ProtectedString> item in entry.Strings)
                this.listBox_CustomFields.Items.Add(new MyFieldObject(item.Key, item.Value.ReadString()));

            this.ShowDialog();
        }
Ejemplo n.º 26
0
        protected AddEntry(Context ctx, IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnFinish finish)
            : base(finish)
        {
            _ctx = ctx;
            _parentGroup = parentGroup;
            _app = app;
            _entry = entry;

            _onFinishToRun = new AfterAdd(app.GetDb(), entry, OnFinishToRun);
        }
Ejemplo n.º 27
0
 public KeeFoxEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
     CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
 {
     KeePassRPCPlugin = keePassRPCPlugin;
     _entry = entry;
     InitializeComponent();
     _advancedListView = advancedListView;
     _pwEntryForm = pwEntryForm;
     _strings = strings;
 }
 private bool compE( PwEntry pe1, PwEntry pe2 )
 {
     // return prec.Compare( pe1, pe2 ) > 0;
     //return pe1.LastModificationTime == pe2.LastModificationTime;
     foreach ( var o in pe1.Strings ) {
         if ( !pe2.Strings.Exists( o.Key ) || pe2.Strings.Get( o.Key ).ReadString() != o.Value.ReadString() )
             return false;
     }
     return true;
 }
 public void SetUpBeforeClassBuiltIn()
 {
     test_bism = new BuiltInStrengthMeasure();
     pwentry1 = new PwEntry(null, false, false);
     pwentry2 = new PwEntry(null, false, false);
     pwentry3 = new PwEntry(null, false, false);
     pwentry4 = new PwEntry(null, false, false);
     pwentry5 = new PwEntry(null, false, false);
     pwentry6 = new PwEntry(null, false, false);
 }
Ejemplo n.º 30
0
        public static bool PerformIntoCurrentWindow(PwEntry pe, PwDatabase pdContext,
                                                    string strSeq)
        {
            if (pe == null)
            {
                Debug.Assert(false); return(false);
            }
            if (!pe.GetAutoTypeEnabled())
            {
                return(false);
            }
            if (!AppPolicy.Try(AppPolicyId.AutoTypeWithoutContext))
            {
                return(false);
            }

            Thread.Sleep(TargetActivationDelay);

            IntPtr hWnd;
            string strWindow;

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

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

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

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

                GetSequencesForWindowEnd(evQueries);

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

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

            return(AutoType.PerformInternal(ctx, strWindow));
        }
Ejemplo n.º 31
0
        private static void ProcessCsvLine(string strLine, PwDatabase pwStorage,
                                           Dictionary <string, PwGroup> dictGroups)
        {
            if (strLine == "\"Bezeichnung\"\t\"User/ID\"\t\"1.Passwort\"\t\"Url/Programm\"\t\"Geändert am\"\t\"Bemerkung\"\t\"2.Passwort\"\t\"Läuft ab\"\t\"Kategorie\"\t\"Eigene Felder\"")
            {
                return;
            }

            string str = strLine;

            if (str.StartsWith("\"") && str.EndsWith("\""))
            {
                str = str.Substring(1, str.Length - 2);
            }
            else
            {
                Debug.Assert(false);
            }

            string[] list = str.Split(new string[] { "\"\t\"" }, StringSplitOptions.None);

            int iOffset;

            if (list.Length == 11)
            {
                iOffset = 0;                               // 1Password Pro 5.99
            }
            else if (list.Length == 10)
            {
                iOffset = -1;                                    // 1PW 6.15
            }
            else if (list.Length > 11)
            {
                iOffset = 0;                                   // Unknown extension
            }
            else
            {
                return;
            }

            string  strGroup = list[9 + iOffset];
            PwGroup pg;

            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);

            pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectTitle,
                               ParseCsvWord(list[1 + iOffset])));
            pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectUserName,
                               ParseCsvWord(list[2 + iOffset])));
            pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectPassword,
                               ParseCsvWord(list[3 + iOffset])));
            pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectUrl,
                               ParseCsvWord(list[4 + iOffset])));
            pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectNotes,
                               ParseCsvWord(list[6 + iOffset])));
            pe.Strings.Set(PwDefs.PasswordField + " 2", new ProtectedString(
                               pwStorage.MemoryProtection.ProtectPassword,
                               ParseCsvWord(list[7 + iOffset])));

            // 1Password Pro only:
            // Debug.Assert(list[9] == list[0]); // Very mysterious format...

            DateTime dt;

            if (ParseDateTime(list[5 + iOffset], out dt))
            {
                pe.CreationTime = pe.LastAccessTime = pe.LastModificationTime = dt;
            }
            else
            {
                Debug.Assert(false);
            }

            if (ParseDateTime(list[8 + iOffset], out dt))
            {
                pe.Expires    = true;
                pe.ExpiryTime = dt;
            }

            AddCustomFields(pe, list[10 + iOffset]);
        }
Ejemplo n.º 32
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);
            }
        }
Ejemplo n.º 33
0
 protected void ExpireEntry(PwEntry entry)
 {
     entry.Expires    = true;
     entry.ExpiryTime = DateTime.Now;
 }
Ejemplo n.º 34
0
 public static void SetKPRPCConfig(this PwEntry entry, EntryConfig newConfig)
 {
     entry.Strings.Set("KPRPC JSON", new ProtectedString(
                           true, Jayrock.Json.Conversion.JsonConvert.ExportToString(newConfig)));
 }
Ejemplo n.º 35
0
        public static EntryConfig GetKPRPCConfig(this PwEntry entry, ProtectedStringDictionary strings, MatchAccuracyMethod mam)
        {
            List <string> dummy = null;

            return(entry.GetKPRPCConfig(strings, ref dummy, mam));
        }
Ejemplo n.º 36
0
 public PwDatabase SafeFindContainerOf(PwEntry peObj)
 {
     // peObj may be null
     return(FindContainerOf(peObj) ?? m_dsActive.Database);
 }
Ejemplo n.º 37
0
        public static OtpAuthData loadDataFromKeeOtp1String(PwEntry entry)
        {
            if (checkUriString(entry.Strings.Get(StringDictionaryKey).ReadString()))
            {
                OtpAuthData data = uriToOtpAuthData(new Uri(entry.Strings.Get(StringDictionaryKey).ReadString()));
                data.loadedFields = new List <string>()
                {
                    StringDictionaryKey
                };
                data.Proprietary = false;
                return(data);
            }
            else
            {
                NameValueCollection parameters = ParseQueryString(entry.Strings.Get(StringDictionaryKey).ReadString());

                if (parameters[KeeOtp1KeyParameter] == null)
                {
                    throw new ArgumentException("Must have a key in the data");
                }

                OtpAuthData data = new OtpAuthData();

                data.loadedFields = new List <string>()
                {
                    StringDictionaryKey
                };

                if (parameters[KeeOtp1TypeParameter] != null)
                {
                    data.Type = (OtpType)Enum.Parse(typeof(OtpType), parameters[KeeOtp1TypeParameter], true);
                }

                if (data.Type == OtpType.Totp && parameters[KeeOtp1EncoderParameter] != null)
                {
                    data.Type = (OtpType)Enum.Parse(typeof(OtpType), parameters[KeeOtp1EncoderParameter], true);
                }

                if (data.Type == OtpType.Steam)
                {
                    data.Proprietary = false;
                }

                if (parameters[KeeOtp1EncodingParameter] != null)
                {
                    data.Encoding = (OtpSecretEncoding)Enum.Parse(typeof(OtpSecretEncoding), parameters[KeeOtp1EncodingParameter], true);
                }

                data.SetPlainSecret(correctPlainSecret(parameters[KeeOtp1KeyParameter].Replace("%3d", "="), data.Encoding));

                if (parameters[KeeOtp1OtpHashModeParameter] != null)
                {
                    data.Algorithm = (OtpHashMode)Enum.Parse(typeof(OtpHashMode), parameters[KeeOtp1OtpHashModeParameter], true);
                }

                if (data.Type == OtpType.Hotp && data.Algorithm != OtpHashMode.Sha1)
                {
                    data.Proprietary = false;
                }

                if (data.Type == OtpType.Totp)
                {
                    data.Period = GetIntOrDefault(parameters, KeeOtp1StepParameter, 30);
                }
                else if (data.Type == OtpType.Hotp)
                {
                    data.Counter = GetIntOrDefault(parameters, KeeOtp1CounterParameter, 0);
                }

                data.Digits = GetIntOrDefault(parameters, KeeOtp1SizeParameter, 6);
                if (data.Type == OtpType.Hotp && data.Digits != 6)
                {
                    data.Proprietary = false;
                }


                return(data);
            }
        }
Ejemplo n.º 38
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            CsvOptions opt = new CsvOptions();

            opt.BackslashIsEscape = false;
            opt.TextQualifier     = char.MaxValue;         // No text qualifier

            CsvStreamReaderEx csv = new CsvStreamReaderEx(strData, opt);
            PwGroup           pg  = pwStorage.RootGroup;

            char[] vGroupSplit = new char[] { '\\' };

            while (true)
            {
                string[] v = csv.ReadLine();
                if (v == null)
                {
                    break;
                }
                if (v.Length < 1)
                {
                    continue;
                }

                for (int i = 0; i < v.Length; ++i)
                {
                    v[i] = ParseString(v[i]);
                }

                if (v[0].StartsWith("\\"))                    // Group
                {
                    string strGroup = v[0].Trim(vGroupSplit); // Also from end
                    if (strGroup.Length > 0)
                    {
                        pg = pwStorage.RootGroup.FindCreateSubTree(strGroup,
                                                                   vGroupSplit);

                        if (v.Length >= 6)
                        {
                            pg.Notes = v[5].Trim();
                        }
                        if ((v.Length >= 5) && (v[4].Trim().Length > 0))
                        {
                            if (pg.Notes.Length > 0)
                            {
                                pg.Notes += Environment.NewLine + Environment.NewLine;
                            }

                            pg.Notes += v[4].Trim();
                        }
                    }
                }
                else                 // Entry
                {
                    PwEntry pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);

                    List <string> l = new List <string>(v);
                    while (l.Count < 8)
                    {
                        Debug.Assert(false);
                        l.Add(string.Empty);
                    }

                    ImportUtil.AppendToField(pe, PwDefs.TitleField, l[0], pwStorage);
                    ImportUtil.AppendToField(pe, PwDefs.UserNameField, l[1], pwStorage);
                    ImportUtil.AppendToField(pe, PwDefs.PasswordField, l[2], pwStorage);
                    ImportUtil.AppendToField(pe, PwDefs.UrlField, l[3], pwStorage);
                    ImportUtil.AppendToField(pe, PwDefs.NotesField, l[4], pwStorage);

                    if (l[5].Length > 0)
                    {
                        ImportUtil.AppendToField(pe, "Custom 1", l[5], pwStorage);
                    }
                    if (l[6].Length > 0)
                    {
                        ImportUtil.AppendToField(pe, "Custom 2", l[6], pwStorage);
                    }
                    if (l[7].Length > 0)
                    {
                        ImportUtil.AppendToField(pe, "Custom 3", l[7], pwStorage);
                    }
                }
            }
        }
Ejemplo n.º 39
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.º 40
0
        private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage)
        {
            PwEntry pe = new PwEntry(true, true);

            pwStorage.RootGroup.AddEntry(pe, true);

            XmlAttributeCollection col = xmlNode.Attributes;

            if (col == null)
            {
                return;
            }

            XmlNode xmlAttrib;

            xmlAttrib = col.GetNamedItem(AttrUser);
            if (xmlAttrib != null)
            {
                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectUserName, PctDecode(xmlAttrib.Value)));
            }
            else
            {
                Debug.Assert(false);
            }

            xmlAttrib = col.GetNamedItem(AttrPassword);
            if (xmlAttrib != null)
            {
                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectPassword, PctDecode(xmlAttrib.Value)));
            }
            else
            {
                Debug.Assert(false);
            }

            xmlAttrib = col.GetNamedItem(AttrURL);
            if (xmlAttrib != null)
            {
                pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
                                   pwStorage.MemoryProtection.ProtectUrl, PctDecode(xmlAttrib.Value)));
            }
            else
            {
                Debug.Assert(false);
            }

            xmlAttrib = col.GetNamedItem(AttrUserFieldName);
            if (xmlAttrib != null)
            {
                pe.Strings.Set(DbUserFieldName, new ProtectedString(
                                   false, PctDecode(xmlAttrib.Value)));
            }
            else
            {
                Debug.Assert(false);
            }

            xmlAttrib = col.GetNamedItem(AttrPasswordFieldName);
            if (xmlAttrib != null)
            {
                pe.Strings.Set(DbPasswordFieldName, new ProtectedString(
                                   false, PctDecode(xmlAttrib.Value)));
            }
            else
            {
                Debug.Assert(false);
            }
        }
 private static bool IsCreditCard(PwEntry pwEntry, Context context)
 {
     return(pwEntry.Strings.Exists("cc-number") ||
            pwEntry.Strings.Exists("cc-csc") ||
            pwEntry.Strings.Exists(context.GetString(Resource.String.TemplateField_CreditCard_CVV)));
 }
Ejemplo n.º 42
0
 public static bool PerformIntoCurrentWindow(PwEntry pe)
 {
     return(PerformIntoCurrentWindow(pe,
                                     Program.MainForm.DocumentManager.SafeFindContainerOf(pe), null));
 }
Ejemplo n.º 43
0
        /// <summary>
        /// The main routine, called when import is selected
        /// </summary>
        /// <param name="pwStorage"></param>
        /// <param name="sInput"></param>
        /// <param name="slLogger"></param>
        public override void Import(PwDatabase pwStorage, System.IO.Stream sInput, KeePassLib.Interfaces.IStatusLogger slLogger)
        {
            try
            {
                FormXml form = new FormXml();

                form.Initialise(pwStorage);

                //	form.GroupName = pwStorage.RootGroup.Name;

                //if (pwStorage.LastSelectedGroup != null)
                //{
                //    form.GroupName = pwStorage.RootGroup.FindGroup(pwStorage.LastSelectedGroup, true).Name;
                //}

                if (form.ShowDialog() == DialogResult.OK)
                {
                    bool overwritePassword = form.Overwrite;
                    bool searchWeb         = form.GetTitles;
                    bool checkMatches      = form.Merge;

                    bool addAutoType = form.AddAutoType;

                    PwIcon iconId = (PwIcon)Enum.Parse(typeof(PwIcon), form.IconName);

                    PwGroup group = form.Group;

                    if (group == null)
                    {
                        group = pwStorage.RootGroup;
                    }

                    try
                    {
                        InternetAccessor internetAccessor = new InternetAccessor();

                        slLogger.StartLogging("Importing Firefox File", false);

                        slLogger.SetText("Reading File", LogStatusType.Info);

                        // Load in the supplied xml document
                        XmlDocument       fireFoxDocument = new XmlDocument();
                        XmlReaderSettings settings        = new XmlReaderSettings();
                        settings.CheckCharacters = false;
                        settings.ValidationType  = ValidationType.None;

                        XmlReader reader = XmlTextReader.Create(sInput, settings);
                        try
                        {
                            fireFoxDocument.Load(reader);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Failed to load the password file. " + Environment.NewLine +
                                                "This may be due to the presence of foreign characters in the data. " + Environment.NewLine +
                                                "Please check the website for help" + Environment.NewLine + Environment.NewLine + ex.Message, ex);
                        }
                        finally
                        {
                            reader.Close();
                        }

                        // Get a collection of nodes that represent each password
                        XmlNodeList fireFoxEntryNodes = fireFoxDocument.SelectNodes("xml/entries/entry");

                        int count = fireFoxEntryNodes.Count;
                        int pos   = 0;

                        // Loop each entry and add it to KeePass
                        foreach (XmlElement fireFoxEntryElement in fireFoxEntryNodes)
                        {
                            if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user
                            {
                                break;
                            }

                            // keep the user informed of progress
                            pos++;
                            slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count)));

                            // gather the data to import
                            string title = fireFoxEntryElement.SelectSingleNode("@host").InnerText;

                            slLogger.SetText(title, LogStatusType.Info);


                            string notes = String.Empty;

                            if (form.IncludeImportNotes)
                            {
                                notes += "Imported from FireFox by the Web Site Advantage FireFox to KeePass Importer" + Environment.NewLine;
                            }

                            string url           = fireFoxEntryElement.SelectSingleNode("@host").InnerText;
                            string formSubmitURL = fireFoxEntryElement.SelectSingleNode("@formSubmitURL").InnerText;

                            if (!String.IsNullOrEmpty(formSubmitURL))
                            {
                                url = formSubmitURL;
                            }

                            string host = url;
                            try
                            {
                                Uri uri = new Uri(url);
                                host = uri.Host;
                            }
                            catch { }

                            string username = fireFoxEntryElement.SelectSingleNode("@user").InnerText;

                            bool newEntry = true;

                            PwEntry pe = null;

                            if (checkMatches)
                            {
                                pe = KeePassHelper.FindMatchingEntry(pwStorage.RootGroup, url, username);
                            }

                            if (pe == null)
                            {
                                // create a new entry
                                pe = new PwEntry(true, true);
                                group.AddEntry(pe, true);
                                slLogger.SetText("Created new entry", LogStatusType.AdditionalInfo);
                            }
                            else
                            {
                                newEntry = false;
                                slLogger.SetText("Found matching entry", LogStatusType.AdditionalInfo);
                            }

                            if (newEntry || overwritePassword)
                            {
                                // set the password
                                pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, fireFoxEntryElement.SelectSingleNode("@password").InnerText));
                            }

                            if (newEntry)
                            {
                                // set all fields
                                pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, title));
                                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, username));
                                pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, url));
                                if (!String.IsNullOrEmpty(notes))
                                {
                                    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, notes));
                                }
                                pe.Expires = false;
                                pe.IconId  = iconId;

                                // Gatter any extra information...

                                if (fireFoxEntryElement.HasAttribute("userFieldName") && fireFoxEntryElement.GetAttribute("userFieldName").Length > 0)
                                {
                                    pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("userFieldName")));
                                }

                                if (fireFoxEntryElement.HasAttribute("usernameField") && fireFoxEntryElement.GetAttribute("usernameField").Length > 0)
                                {
                                    pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("usernameField")));
                                }

                                if (fireFoxEntryElement.HasAttribute("passFieldName") && fireFoxEntryElement.GetAttribute("passFieldName").Length > 0)
                                {
                                    pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passFieldName")));
                                }

                                if (fireFoxEntryElement.HasAttribute("passwordField") && fireFoxEntryElement.GetAttribute("passwordField").Length > 0)
                                {
                                    pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passwordField")));
                                }

                                if (fireFoxEntryElement.HasAttribute("httpRealm") && fireFoxEntryElement.GetAttribute("httpRealm").Length > 0)
                                {
                                    pe.Strings.Set("HttpRealm", new ProtectedString(false, fireFoxEntryElement.GetAttribute("httpRealm")));
                                }

                                if (fireFoxEntryElement.HasAttribute("formSubmitURL") && fireFoxEntryElement.GetAttribute("formSubmitURL").Length > 0)
                                {
                                    pe.Strings.Set("LoginFormDomain", new ProtectedString(false, fireFoxEntryElement.GetAttribute("formSubmitURL")));
                                }
                            }

                            string webTitle = null;
                            // if new or the title is the same as the url then we should try and get the title
                            if (searchWeb)
                            {
                                // test if new or entry has url as title
                                if ((newEntry || pe.Strings.Get(PwDefs.TitleField).ReadString() == pe.Strings.Get(PwDefs.UrlField).ReadString()))
                                {
                                    // get the pages title
                                    slLogger.SetText("Accessing website for title", LogStatusType.AdditionalInfo);

                                    webTitle = internetAccessor.ScrapeTitle(url);

                                    if (!String.IsNullOrEmpty(webTitle))
                                    {
                                        slLogger.SetText("Title set from internet to " + webTitle, LogStatusType.AdditionalInfo);

                                        pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, webTitle));
                                    }
                                }
                            }

                            if (addAutoType)
                            {
                                KeePassHelper.InsertAutoType(pe, "*" + host + "*", KeePassUtilities.AutoTypeSequence());
                            }

                            if (webTitle != null && addAutoType)
                            {
                                KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence());
                            }
                        }
                    }
                    finally
                    {
                        slLogger.EndLogging();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage.ShowErrorMessage("Importer Xml", "Import Failed", ex);
            }
        }
Ejemplo n.º 44
0
 public static bool PerformIntoPreviousWindow(Form fCurrent, PwEntry pe,
                                              PwDatabase pdContext)
 {
     return(PerformIntoPreviousWindow(fCurrent, pe, pdContext, null));
 }
Ejemplo n.º 45
0
        public override void Run()
        {
            //check if we will run into problems. Then finish with error before we start doing anything.
            foreach (var _elementToMove in _elementsToMove)
            {
                PwGroup pgParent = _elementToMove.ParentGroup;
                if (pgParent != _targetGroup)
                {
                    if (pgParent != null)
                    {
                        PwGroup group = _elementToMove as PwGroup;
                        if (group != null)
                        {
                            if ((_targetGroup == group) || (_targetGroup.IsContainedIn(group)))
                            {
                                Finish(false, _app.GetResourceString(UiStringKey.CannotMoveGroupHere));
                                return;
                            }
                        }
                    }
                }
            }

            HashSet <Database> removeDatabases = new HashSet <Database>();
            Database           addDatabase     = _app.FindDatabaseForElement(_targetGroup);

            if (addDatabase == null)
            {
                Finish(false, "Did not find target database. Did you lock it?");
                return;
            }

            foreach (var elementToMove in _elementsToMove)
            {
                _app.DirtyGroups.Add(elementToMove.ParentGroup);


                PwGroup pgParent = elementToMove.ParentGroup;
                if (pgParent != _targetGroup)
                {
                    if (pgParent != null) // Remove from parent
                    {
                        PwEntry entry = elementToMove as PwEntry;
                        if (entry != null)
                        {
                            var dbRem = _app.FindDatabaseForElement(entry);
                            removeDatabases.Add(dbRem);
                            dbRem.EntriesById.Remove(entry.Uuid);
                            dbRem.Elements.Remove(entry);
                            pgParent.Entries.Remove(entry);
                            _targetGroup.AddEntry(entry, true, true);
                            addDatabase.EntriesById.Add(entry.Uuid, entry);
                            addDatabase.Elements.Add(entry);
                        }
                        else
                        {
                            PwGroup group = (PwGroup)elementToMove;
                            if ((_targetGroup == group) || (_targetGroup.IsContainedIn(group)))
                            {
                                Finish(false, _app.GetResourceString(UiStringKey.CannotMoveGroupHere));
                                return;
                            }

                            var dbRem = _app.FindDatabaseForElement(@group);
                            if (dbRem == null)
                            {
                                Finish(false, "Did not find source database. Did you lock it?");
                                return;
                            }

                            dbRem.GroupsById.Remove(group.Uuid);
                            dbRem.Elements.Remove(group);
                            removeDatabases.Add(dbRem);
                            pgParent.Groups.Remove(group);
                            _targetGroup.AddGroup(group, true, true);
                            addDatabase.GroupsById.Add(group.Uuid, group);
                            addDatabase.Elements.Add(group);
                        }
                    }
                }
            }



            //first save the database where we added the elements
            var allDatabasesToSave = new List <Database> {
                addDatabase
            };

            //then all databases where we removed elements:
            removeDatabases.RemoveWhere(db => db == addDatabase);
            allDatabasesToSave.AddRange(removeDatabases);

            int  indexToSave     = 0;
            bool allSavesSuccess = true;

            void ContinueSave(bool success, string message, Activity activeActivity)
            {
                allSavesSuccess &= success;
                indexToSave++;
                if (indexToSave == allDatabasesToSave.Count)
                {
                    OnFinishToRun.SetResult(allSavesSuccess);
                    OnFinishToRun.Run();
                    return;
                }
                SaveDb saveDb = new SaveDb(_ctx, _app, allDatabasesToSave[indexToSave], new ActionOnFinish(activeActivity, ContinueSave), false);

                saveDb.SetStatusLogger(StatusLogger);
                saveDb.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
                saveDb.Run();
            }

            SaveDb save = new SaveDb(_ctx, _app, allDatabasesToSave[0], new ActionOnFinish(ActiveActivity, ContinueSave), false);

            save.SetStatusLogger(StatusLogger);
            save.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
            save.Run();
        }
Ejemplo n.º 46
0
 public static bool PerformIntoPreviousWindow(Form fCurrent, PwEntry pe)
 {
     return(PerformIntoPreviousWindow(fCurrent, pe,
                                      Program.MainForm.DocumentManager.SafeFindContainerOf(pe), null));
 }
Ejemplo n.º 47
0
        public static EntryConfig GetKPRPCConfig(this PwEntry entry, MatchAccuracyMethod mam)
        {
            List <string> dummy = null;

            return(entry.GetKPRPCConfig(null, ref dummy, mam));
        }
Ejemplo n.º 48
0
 public static PwEntryView GetInstance(GroupBaseActivity act, PwEntry pw, int pos)
 {
     return(new PwEntryView(act, pw, pos));
 }
Ejemplo n.º 49
0
 public HostPwEntry(PwEntry pwEntry, PwDatabase pwDatabase, IFieldMapper fieldMapper)
 {
     this.pwEntry      = pwEntry;
     this.pwDatabase   = pwDatabase;
     this.fieldsMapper = fieldMapper;
 }
Ejemplo n.º 50
0
        private void PopulateView(View ev, PwEntry pw, int pos)
        {
            _entry = pw;
            _pos   = pos;
            ev.FindViewById(Resource.Id.icon).Visibility       = ViewStates.Visible;
            ev.FindViewById(Resource.Id.check_mark).Visibility = ViewStates.Invisible;

            Database db = App.Kp2a.FindDatabaseForElement(_entry);

            ImageView iv        = (ImageView)ev.FindViewById(Resource.Id.icon);
            bool      isExpired = pw.Expires && pw.ExpiryTime < DateTime.Now;

            if (isExpired)
            {
                db.DrawableFactory.AssignDrawableTo(iv, Context, db.KpDatabase, PwIcon.Expired, PwUuid.Zero, false);
            }
            else
            {
                db.DrawableFactory.AssignDrawableTo(iv, Context, db.KpDatabase, pw.IconId, pw.CustomIconUuid, false);
            }

            String title = pw.Strings.ReadSafe(PwDefs.TitleField);
            var    str   = new SpannableString(title);

            if (isExpired)
            {
                str.SetSpan(new StrikethroughSpan(), 0, title.Length, SpanTypes.ExclusiveExclusive);
            }
            _textView.TextFormatted = str;

            if (_defaultTextColor == null)
            {
                _defaultTextColor = _textView.TextColors.DefaultColor;
            }

            if (_groupActivity.IsBeingMoved(_entry.Uuid))
            {
                int elementBeingMoved = Context.Resources.GetColor(Resource.Color.element_being_moved);
                _textView.SetTextColor(new Color(elementBeingMoved));
            }
            else
            {
                _textView.SetTextColor(new Color((int)_defaultTextColor));
            }

            String detail = pw.Strings.ReadSafe(PwDefs.UserNameField);

            detail = SprEngine.Compile(detail, new SprContext(_entry, db.KpDatabase, SprCompileFlags.All));

            if ((_showDetail == false) || (String.IsNullOrEmpty(detail)))
            {
                _textviewDetails.Visibility = ViewStates.Gone;
            }
            else
            {
                var strDetail = new SpannableString(detail);

                if (isExpired)
                {
                    strDetail.SetSpan(new StrikethroughSpan(), 0, detail.Length, SpanTypes.ExclusiveExclusive);
                }
                _textviewDetails.TextFormatted = strDetail;

                _textviewDetails.Visibility = ViewStates.Visible;
            }

            if ((!_showGroupFullPath) || (!_isSearchResult))
            {
                _textgroupFullPath.Visibility = ViewStates.Gone;
            }

            else
            {
                String groupDetail = pw.ParentGroup.GetFullPath();
                if (App.Kp2a.OpenDatabases.Count() > 1)
                {
                    groupDetail += "(" + App.Kp2a.GetFileStorage(db.Ioc).GetDisplayName(db.Ioc) + ")";
                }

                var strGroupDetail = new SpannableString(groupDetail);

                if (isExpired)
                {
                    strGroupDetail.SetSpan(new StrikethroughSpan(), 0, groupDetail.Length, SpanTypes.ExclusiveExclusive);
                }
                _textgroupFullPath.TextFormatted = strGroupDetail;

                _textgroupFullPath.Visibility = ViewStates.Visible;
            }
        }
Ejemplo n.º 51
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.º 52
0
 public CopyEntry(Activity ctx, IKp2aApp app, PwEntry entry, OnFinish finish)
     : base(ctx, app, CreateCopy(entry, app), entry.ParentGroup, finish)
 {
 }
Ejemplo n.º 53
0
 public void ConvertView(PwEntry pw, int pos)
 {
     PopulateView(this, pw, pos);
 }
Ejemplo n.º 54
0
        private static bool Execute(AutoTypeCtx ctx)
        {
            if (ctx == null)
            {
                Debug.Assert(false); return(false);
            }

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

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

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

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

            PwDatabase pwDatabase = ctx.Database;

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

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

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

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

            Application.DoEvents();

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

            if (args.Sequence.Length > 0)
            {
                try { SendInputEx.SendKeysWait(args.Sequence, args.SendObfuscated); }
                catch (Exception excpAT)
                {
                    MessageService.ShowWarning(args.Sequence +
                                               MessageService.NewParagraph + excpAT.Message);
                }
            }

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

            MainForm mf = Program.MainForm;

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

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

            return(true);
        }
Ejemplo n.º 55
0
 internal static PwEntry WithValidTotpSettings(this PwEntry pwEntry)
 {
     pwEntry.Strings.Set(Localization.Strings.TOTPSeed, new ProtectedString(false, "JBSWY3DPEHPK3PXP"));
     pwEntry.Strings.Set(Localization.Strings.TOTPSettings, new ProtectedString(false, "30;6"));
     return(pwEntry);
 }
Ejemplo n.º 56
0
 public PwEntryBuffer(PwEntry entry)
 {
     mEntry = entry;
 }
Ejemplo n.º 57
0
 internal static PwEntry WithInvalidTotpSettings(this PwEntry pwEntry)
 {
     pwEntry.Strings.Set(Localization.Strings.TOTPSeed, new ProtectedString(false, "11111-"));
     pwEntry.Strings.Set(Localization.Strings.TOTPSettings, new ProtectedString(false, "-1;10"));
     return(pwEntry);
 }
Ejemplo n.º 58
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            string str = Preprocess(sInput);

            PwMemory2008XmlFile_Priv f = null;

            using (MemoryStream ms = new MemoryStream(StrUtil.Utf8.GetBytes(str), false))
            {
                f = XmlUtilEx.Deserialize <PwMemory2008XmlFile_Priv>(ms);
            }
            if ((f == null) || (f.Cells == null))
            {
                return;
            }

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

            for (int iLine = 2; iLine < f.Cells.Length; ++iLine)
            {
                string[] vCells = f.Cells[iLine];
                if ((vCells == null) || (vCells.Length != 6))
                {
                    continue;
                }
                if ((vCells[1] == null) || (vCells[2] == null) ||
                    (vCells[3] == null) || (vCells[4] == null))
                {
                    continue;
                }

                string  strGroup = vCells[4];
                PwGroup pg;
                if (strGroup == ".")
                {
                    pg = pwStorage.RootGroup;
                }
                else if (vGroups.ContainsKey(strGroup))
                {
                    pg = vGroups[strGroup];
                }
                else
                {
                    pg      = new PwGroup(true, true);
                    pg.Name = strGroup;
                    pwStorage.RootGroup.AddGroup(pg, true);

                    vGroups[strGroup] = pg;
                }

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

                if (vCells[1] != ".")
                {
                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectTitle, vCells[1]));
                }
                if (vCells[2] != ".")
                {
                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectUserName, vCells[2]));
                }
                if (vCells[3] != ".")
                {
                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                                       pwStorage.MemoryProtection.ProtectPassword, vCells[3]));
                }
            }
        }
Ejemplo n.º 59
0
 public static bool PerformIntoCurrentWindow(PwEntry pe, PwDatabase pdContext)
 {
     return(PerformIntoCurrentWindow(pe, pdContext, null));
 }
Ejemplo n.º 60
-1
		private static void ProcessCsvLine(string strLine, PwDatabase pwStorage)
		{
			List<string> list = ImportUtil.SplitCsvLine(strLine, ",");
			Debug.Assert(list.Count == 6);

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

			if(list.Count == 6)
			{
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectTitle,
					ParseCsvWord(list[0], false)));
				pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUserName,
					ParseCsvWord(list[1], false)));
				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectPassword,
					ParseCsvWord(list[2], false)));
				pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUrl,
					ParseCsvWord(list[3], false)));
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes,
					ParseCsvWord(list[4], true)));

				DateTime dt;
				if(DateTime.TryParse(ParseCsvWord(list[5], false), out dt))
				{
					pe.CreationTime = pe.LastAccessTime = pe.LastModificationTime = dt;
				}
				else { Debug.Assert(false); }
			}
			else throw new FormatException("Invalid field count!");
		}