Пример #1
0
        /// <summary>
        /// Populates the Group based combo and sets the selected item to the last one selected in KeePass
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="pwStorage"></param>
        public static void InitialiseGroupComboBox(ComboBox comboBox, PwDatabase pwStorage)
        {
            KeePassHelper.AddGroupToComboBox(comboBox, pwStorage.RootGroup, 0);

            KeePassHelper.SetComboBoxGroup(comboBox, pwStorage.RootGroup.FindGroup(pwStorage.LastSelectedGroup, true));
        }
        /// <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
            {
                Form1 form = new Form1();

                form.Initialise(pwStorage);

                if (form.ShowDialog() == DialogResult.OK)
                {
                    // return;
                    bool   overwritePassword = form.Overwrite;
                    bool   searchWeb         = form.GetTitles;
                    bool   checkMatches      = form.Merge;
                    string masterPassword    = form.Password;

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

                    string profilePath = form.ProfilePath;

                    if (String.IsNullOrEmpty(profilePath))
                    {
                        MessageBox.Show("No Profile Selected. Use Load More Profiles", "Profile Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Import(pwStorage, sInput, slLogger); // bit of a hack!
                        return;
                    }

                    PwGroup group = form.Group;

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

                    //     return;

                    try
                    {
                        InternetAccessor internetAccessor = new InternetAccessor();

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

                        slLogger.SetText("Logging In", LogStatusType.Info);

                        FirefoxProfile profile = new FirefoxProfile(profilePath);

                        profile.Login(masterPassword);

                        slLogger.SetText("Reading Signon file", LogStatusType.Info);


                        FirefoxSignonsFile signonsFile = profile.GetSignonsFile(masterPassword);


                        slLogger.SetText("Processing Passwords", LogStatusType.Info);

                        int count = signonsFile.SignonSites.Count;
                        int pos   = 0;

                        //  return;

                        // Loop each entry and add it to KeePass
                        foreach (FirefoxSignonSite signonSite in signonsFile.SignonSites)
                        {
                            // keep the user informed of progress
                            pos++;

                            foreach (FirefoxSignon signon in signonSite.Signons)
                            {
                                if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user
                                {
                                    break;
                                }


                                slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count)));


                                string notes = String.Empty;

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

                                // gather the data to import

                                string title = signonSite.Site;

                                // PATCH: supplied by Sarel Botha
                                // remove protocol from site so that it works with new KeepassHTTP
                                if (title.StartsWith("http://"))
                                {
                                    title = title.Substring(7);
                                }
                                if (title.StartsWith("https://"))
                                {
                                    title = title.Substring(8);
                                }

                                // remove port number if the title contains it so that it will work with new KeepassHTTP
                                if (title.Contains(":"))
                                {
                                    title = title.Substring(0, title.IndexOf(':'));
                                }
                                // PATCH END

                                string url = signonSite.Site;

                                if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                {
                                    title = signon.LoginFormDomain;
                                    url   = signon.LoginFormDomain;
                                }

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

                                slLogger.SetText(title, LogStatusType.Info);


                                string username = signon.UserName;

                                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, signon.Password));
                                }

                                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 (!String.IsNullOrEmpty(signon.UserNameField))
                                    {
                                        pe.Strings.Set("UserNameField", new ProtectedString(false, signon.UserNameField));
                                    }

                                    if (!String.IsNullOrEmpty(signon.PasswordField))
                                    {
                                        pe.Strings.Set("PasswordField", new ProtectedString(false, signon.PasswordField));
                                    }

                                    if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                    {
                                        pe.Strings.Set("LoginFormDomain", new ProtectedString(false, signon.LoginFormDomain));
                                    }
                                }

                                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));
                                        }
                                    }
                                    //else
                                    //{
                                    //    // Entry has a good title, keep it incase there are other ones for this site
                                    //    title = pe.Strings.Get(PwDefs.TitleField).ReadString();
                                    //}
                                }
                                // return;


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

                                // return;

                                if (webTitle != null && addAutoType)
                                {
                                    KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence());
                                }
                            }
                        }
                    }
                    finally
                    {
                        slLogger.EndLogging();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Failed to Validate Password"))
                {
                    MessageBox.Show(ex.Message, "Import Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    ErrorMessage.ShowErrorMessage("Importer", "Import Failed", ex);
                }
            }
        }
Пример #3
0
 public void Initialise(PwDatabase pwStorage)
 {
     KeePassHelper.InitialiseGroupComboBox(this.comboBoxGroup, pwStorage);
 }
        /// <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 = "HOST";

                            XmlNode hostNode          = fireFoxEntryElement.SelectSingleNode("@host");
                            XmlNode formSubmitURLNode = fireFoxEntryElement.SelectSingleNode("@formSubmitURL");
                            XmlNode userNode          = fireFoxEntryElement.SelectSingleNode("@user");
                            XmlNode passwordNode      = fireFoxEntryElement.SelectSingleNode("@password");

                            if (hostNode != null)
                            {
                                title = hostNode.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 = String.Empty;

                            if (hostNode != null)
                            {
                                url = hostNode.InnerText;
                            }

                            string formSubmitURL = String.Empty;

                            if (formSubmitURLNode != null)
                            {
                                formSubmitURL = formSubmitURLNode.InnerText;
                            }

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

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

                            string username = String.Empty;

                            if (userNode != null)
                            {
                                username = userNode.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
                                if (passwordNode != null)
                                {
                                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, passwordNode.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))
                                    {
                                        // PATCH: supplied by Sarel Botha
                                        // remove protocol from site so that it works with new KeepassHTTP
                                        if (webTitle.StartsWith("http://"))
                                        {
                                            webTitle = webTitle.Substring(7);
                                        }
                                        if (webTitle.StartsWith("https://"))
                                        {
                                            webTitle = webTitle.Substring(8);
                                        }

                                        // remove port number if the title contains it so that it will work with new KeepassHTTP
                                        if (webTitle.Contains(":"))
                                        {
                                            webTitle = webTitle.Substring(0, webTitle.IndexOf(':'));
                                        }
                                        // PATCH END

                                        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)
            {
                if (ex.Message.Contains("Failed to Validate Password"))
                {
                    MessageBox.Show(ex.Message, "Import Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    ErrorMessage.ShowErrorMessage("Importer Xml", "Import Failed", ex);
                }
            }
        }
 public ImportDialog(PwDatabase pwStorage)
 {
     InitializeComponent();
     KeePassHelper.InitialiseGroupComboBox(this.comboGroup, pwStorage);
 }
Пример #6
0
        public static async Task AddEntryAsync(Signon signon, ImportDialog form, PwDatabase db, IStatusLogger logger)
        {
            logger.SetText("Processing signon " + signon.Username + " @ " + signon.Hostname, LogStatusType.Info);

            PwGroup group    = form.Group ?? db.RootGroup;
            PwEntry entry    = null;
            var     newEntry = true;

            if (form.CheckExisting) // TODO: Search using both the Hostname and FormSubmitUrl.
            {
                entry = KeePassHelper.FindMatchingEntry(db.RootGroup, signon.Hostname, signon.Username);
            }

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

            if (newEntry || form.Overwrite)
            {
                // Set the password.
                entry.Strings.Set(
                    PwDefs.PasswordField,
                    new ProtectedString(db.MemoryProtection.ProtectPassword, signon.Password)
                    );
            }

            if (!newEntry)
            {
                return;
            }

            string title = signon.Hostname;

            try
            {
                var uri = new Uri(signon.Hostname);
                title = uri.Host;
            }
            catch (UriFormatException ex) // TODO: May need to also catch ArgumentException
            {
                logger.SetText("The URL of the signon could not be parsed", LogStatusType.Warning);
            }

            if (form.GetTitles || form.GetIcons)
            {
                logger.SetText("Scraping " + signon.Hostname + " for the title and/or icon", LogStatusType.AdditionalInfo);

                ValueTuple <string, byte[]> results = await WebScraper.ScrapeAsync(
                    signon.Hostname,
                    form.GetTitles,
                    form.GetIcons
                    ).ConfigureAwait(false);

                string titleWeb = results.Item1;
                byte[] iconData = results.Item2;

                if (!string.IsNullOrWhiteSpace(titleWeb))
                {
                    title = titleWeb.Trim();
                }

                if (iconData != null)
                {
                    var icon = new PwCustomIcon(new PwUuid(true), iconData);
                    db.CustomIcons.Add(icon);
                    entry.CustomIconUuid = icon.Uuid;
                }
            }

            // Set all fields.
            entry.Strings.Set(
                PwDefs.TitleField,
                new ProtectedString(db.MemoryProtection.ProtectTitle, title)
                );
            entry.Strings.Set(
                PwDefs.UserNameField,
                new ProtectedString(db.MemoryProtection.ProtectUserName, signon.Username)
                );
            entry.Strings.Set
                (PwDefs.UrlField,
                new ProtectedString(db.MemoryProtection.ProtectUrl, signon.Hostname)
                );

            if (form.IncludeNotes)
            {
                entry.Strings.Set(
                    PwDefs.NotesField,
                    new ProtectedString(db.MemoryProtection.ProtectNotes, Note));
            }

            entry.Expires              = false;
            entry.IconId               = form.EntryIcon;
            entry.CreationTime         = signon.TimeCreated ?? entry.CreationTime;
            entry.LastAccessTime       = signon.TimeLastUsed ?? entry.LastAccessTime;
            entry.LastModificationTime = signon.TimePasswordChanged ?? entry.LastModificationTime;
            entry.UsageCount           = signon.TimesUsed;
        }