Beispiel #1
0
        public bool IsEnabled(EntryConfig entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var entryName = entry.Name.ToLowerInvariant();

            if (entryName == "domain")
            {
                return(_firewallPolicy.DefaultOutboundAction[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN] == NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
            }
            else if (entryName == "private")
            {
                return(_firewallPolicy.DefaultOutboundAction[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE] == NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
            }
            else if (entryName == "public")
            {
                return(_firewallPolicy.DefaultOutboundAction[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC] == NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
            }
            else
            {
                return(entry.Rules.All(rule => _firewallPolicy.Rules.Item(rule).Enabled));
            }
        }
        public MatchAccuracyMethod SelectsCorrectMatchAccuracyMethod(
            string urlSearch,
            MatchAccuracyMethod entryMam,
            MatchAccuracyMethod defaultMam,
            string[] overrideURLs = null,
            MatchAccuracyMethod[] overrideMethods = null)
        {
            var pwe  = new PwEntry(true, true);
            var conf = new EntryConfig(entryMam);

            pwe.SetKPRPCConfig(conf);
            var urlSummary = URLSummary.FromURL(urlSearch);
            var dbConf     = new DatabaseConfig()
            {
                DefaultMatchAccuracy = defaultMam
            };

            if (overrideURLs != null)
            {
                for (int i = 0; i < overrideURLs.Length; i++)
                {
                    dbConf.MatchedURLAccuracyOverrides.Add(overrideURLs[i], overrideMethods[i]);
                }
            }

            return(pwe.GetMatchAccuracyMethod(urlSummary, dbConf));
        }
Beispiel #3
0
        public void Toggle(EntryConfig entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var entryName = entry.Name.ToLowerInvariant();

            if (entryName == "domain")
            {
                ToggleProfileRule(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN);
            }
            else if (entryName == "private")
            {
                ToggleProfileRule(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE);
            }
            else if (entryName == "public")
            {
                ToggleProfileRule(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC);
            }
            else
            {
                ToggleRules(entry.Rules);
            }
        }
Beispiel #4
0
 public static EntryConfig GetKPRPCConfig(this PwEntry entry, ProtectedStringDictionary strings, ref List<string> configErrors)
 {
     if (strings == null)
         strings = entry.Strings;
     EntryConfig conf = null;
     string json = strings.ReadSafe("KPRPC JSON");
     if (string.IsNullOrEmpty(json))
         conf = new EntryConfig();
     else
     {
         try
         {
             conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
         }
         catch (Exception)
         {
             var url = strings.ReadSafe("URL");
             if (string.IsNullOrEmpty(url))
                 url = "<unknown>";
             if (configErrors != null)
             {
                 string entryUserName = strings.ReadSafe(PwDefs.UserNameField);
                 //entryUserName = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(entry, entryUserName, db);
                 configErrors.Add("Username: "******". URL: " + url);
             }
             else
             {
                 MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KPRPC JSON' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + url + " and the full configuration data is: " + json, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             return null;
         }
     }
     return conf;
 }
        public KeeFoxEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
                                      CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
        {
            KeePassRPCPlugin = keePassRPCPlugin;
            _entry           = entry;
            InitializeComponent();
            _pwEntryForm = pwEntryForm;
            _strings     = strings;
            string json = strings.ReadSafe("KPRPC JSON");

            if (string.IsNullOrEmpty(json))
            {
                _conf = new EntryConfig();
            }
            else
            {
                try
                {
                    _conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this.", "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Beispiel #6
0
 private void UpdateKPRPCJSON(EntryConfig _conf)
 {
     // if the config is identical to an empty (default) config, only update if a JSON string already exists
     if (!_conf.Equals(new EntryConfig()) || _strings.GetKeys().Contains("KPRPC JSON"))
     {
         changeAdvancedString("KPRPC JSON", Jayrock.Json.Conversion.JsonConvert.ExportToString(_conf), true);
     }
 }
Beispiel #7
0
        private void FileToFolder(EntryConfig entry)
        {
            EnsureFolder(entry.DestinationFolder);
            var destination = Path.Combine(entry.DestinationFolder, Path.GetFileName(entry.SourceFile));

            Log.Information($"Copying file {entry.SourceFile} to {destination} ...");
            File.Copy(entry.SourceFile, destination, true);
        }
Beispiel #8
0
        internal void SetEntryConfig(PwEntry e, EntryConfig c)
        {
            var serializer = NewJsonSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, c);
            e.Strings.Set(KeePassNatMsgName, new ProtectedString(false, writer.ToString()));
            e.Touch(true);
            UpdateUI(e.ParentGroup);
        }
        internal void SetEntryConfig(PwEntry e, EntryConfig c)
        {
            var serializer = NewJsonSerializer();
            var writer     = new StringWriter();

            serializer.Serialize(writer, c);
            e.CustomData.Set(SettingKey, writer.ToString());
            e.Touch(true);
            UpdateUI(e.ParentGroup);
        }
Beispiel #10
0
 public KeeFoxEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
                               CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
 {
     KeePassRPCPlugin = keePassRPCPlugin;
     _entry           = entry;
     InitializeComponent();
     _pwEntryForm = pwEntryForm;
     _strings     = strings;
     _conf        = entry.GetKPRPCConfig(strings);
 }
 public KeeFoxEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
     CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
 {
     KeePassRPCPlugin = keePassRPCPlugin;
     _entry = entry;
     InitializeComponent();
     _pwEntryForm = pwEntryForm;
     _strings = strings;
     _conf = entry.GetKPRPCConfig(strings);
 }
Beispiel #12
0
 public KeeEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
                            CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
 {
     KeePassRPCPlugin = keePassRPCPlugin;
     _entry           = entry;
     InitializeComponent();
     _pwEntryForm = pwEntryForm;
     _strings     = strings;
     _dbConf      = KeePassRPCPlugin._host.Database.GetKPRPCConfig();
     _conf        = entry.GetKPRPCConfig(strings, _dbConf.DefaultMatchAccuracy);
 }
Beispiel #13
0
 private void FolderToFolder(EntryConfig entry)
 {
     // Copy files
     foreach (var source in Directory.GetFiles(entry.SourceFolder, "*.*", SearchOption.AllDirectories))
     {
         var destination = source.Replace(entry.SourceFolder, entry.DestinationFolder);
         EnsureFolder(Path.GetDirectoryName(destination));
         Log.Information($"Copying file {source} to {destination} ...");
         File.Copy(source, destination, true);
     }
 }
        public MatchAccuracyEnum CalculatesCorrectMatchAccuracyScore(string urlEntry, string urlSearch, MatchAccuracyMethod entryMam)
        {
            var pwe = new PwEntry(true, true);

            pwe.Strings.Set("URL", new ProtectedString(false, urlEntry));
            var conf = new EntryConfig(entryMam);

            pwe.SetKPRPCConfig(conf);
            var urlSummary = URLSummary.FromURL(urlSearch);

            return((MatchAccuracyEnum)KeePassRPCService.BestMatchAccuracyForAnyURL(pwe, conf, urlSearch, urlSummary, entryMam));
        }
Beispiel #15
0
 private void ProcessEntry(EntryConfig entry)
 {
     if (!string.IsNullOrEmpty(entry.SourceFolder) && !string.IsNullOrEmpty(entry.DestinationFolder))
     {
         FolderToFolder(entry);
     }
     else if (!string.IsNullOrEmpty(entry.SourceFile) && !string.IsNullOrEmpty(entry.DestinationFile))
     {
         FileToFile(entry);
     }
     else if (!string.IsNullOrEmpty(entry.SourceFile) && !string.IsNullOrEmpty(entry.DestinationFolder))
     {
         FileToFolder(entry);
     }
 }
Beispiel #16
0
        public static EntryConfig GetKPRPCConfig(this PwEntry entry, ProtectedStringDictionary strings, ref List <string> configErrors)
        {
            if (strings == null)
            {
                strings = entry.Strings;
            }
            EntryConfig conf = null;
            string      json = strings.ReadSafe("KPRPC JSON");

            if (string.IsNullOrEmpty(json))
            {
                conf = new EntryConfig();
            }
            else
            {
                try
                {
                    conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                }
                catch (Exception)
                {
                    var url = strings.ReadSafe("URL");
                    if (string.IsNullOrEmpty(url))
                    {
                        url = "<unknown>";
                    }
                    if (configErrors != null)
                    {
                        string entryUserName = strings.ReadSafe(PwDefs.UserNameField);
                        //entryUserName = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(entry, entryUserName, db);
                        configErrors.Add("Username: "******". URL: " + url);
                    }
                    else
                    {
                        MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KPRPC JSON' advanced string. Please ask for help on https://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + url + " and the full configuration data is: " + json, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    return(null);
                }
            }
            return(conf);
        }
 public KeeFoxEntryUserControl(KeePassRPCExt keePassRPCPlugin, PwEntry entry,
     CustomListViewEx advancedListView, PwEntryForm pwEntryForm, ProtectedStringDictionary strings)
 {
     KeePassRPCPlugin = keePassRPCPlugin;
     _entry = entry;
     InitializeComponent();
     _pwEntryForm = pwEntryForm;
     _strings = strings;
     string json = strings.ReadSafe("KPRPC JSON");
     if (string.IsNullOrEmpty(json))
         _conf = new EntryConfig();
     else
     {
         try
         {
             _conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
         }
         catch (Exception)
         {
             MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this.", "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
 }
Beispiel #18
0
        static void RunOptions(Options options)
        {
            if (string.IsNullOrEmpty(options.InputExcelDir) && string.IsNullOrEmpty(options.InputExcelFile))
            {
                Console.WriteLine("the dir or the path of excel is empty", Color.Red);
                return;
            }
            if (!Directory.Exists(options.OutputDir))
            {
                DirectoryInfo dInfo = Directory.CreateDirectory(options.OutputDir);
                if (!dInfo.Exists)
                {
                    Console.WriteLine($"the dir({options.OutputDir}) is not found", Color.Red);
                    return;
                }
            }
            if (options.TargetType == OutputTargetType.Lua)
            {
                if (string.IsNullOrEmpty(options.LuaTemplatePath))
                {
                    Console.WriteLine($"the path of LuaTemplatePath is empty", Color.Red);
                    return;
                }
                if (!File.Exists(options.LuaTemplatePath))
                {
                    Console.WriteLine($"the template({options.LuaTemplatePath}) is not found", Color.Red);
                    return;
                }
            }
            WDBFromExcelReader.logHandler = (logType, message) =>
            {
                if (options.IsPrintLog && logType == LogType.Info)
                {
                    Console.WriteLine(message, Color.White);
                }
                else if (logType == LogType.Warning)
                {
                    Console.WriteLine(message, Color.Yellow);
                }
                else if (logType == LogType.Error)
                {
                    Console.WriteLine(message, Color.Red);
                }
            };

            WDBExcelStyle readStyle = new WDBExcelStyle();

            readStyle.TargetPlatform = options.PlatformType;

            WDBSheet[] sheets = null;
            if (!string.IsNullOrEmpty(options.InputExcelDir))
            {
                sheets = WDBFromExcelReader.ReadFromDirectory(options.InputExcelDir, readStyle);
            }
            else if (!string.IsNullOrEmpty(options.InputExcelFile))
            {
                sheets = WDBFromExcelReader.ReadFromFile(options.InputExcelFile, readStyle);
            }
            WDBFromExcelReader.logHandler = null;
            if (sheets == null || sheets.Length == 0)
            {
                Console.WriteLine("the sheet is not found", Color.Red);
                return;
            }
            if (options.IsNeedVerify)
            {
                if (!WDBVerify.VerifySheets(sheets, out var errors))
                {
                    Console.WriteLine("Some error was found in sheets");
                    if (errors != null && errors.Length > 0)
                    {
                        foreach (var error in errors)
                        {
                            Console.WriteLine("    " + error, Color.Red);
                        }
                    }
                    return;
                }
            }

            foreach (var sheet in sheets)
            {
                if (options.TargetType == OutputTargetType.NDB)
                {
                    WDBToNDBWriter.WriteToNDBFile(options.OutputDir, sheet);
                }
                else if (options.TargetType == OutputTargetType.Lua)
                {
                    string      luaPath = $"{options.OutputDir}/{sheet.Name}.{options.LuaExtension}";
                    EntryConfig config  = new EntryConfig()
                    {
                        CodeOutputPath = @"D:\"
                    };
                    string templateContent = File.ReadAllText(options.LuaTemplatePath);
                    WDBToLuaWriter.WriteToLuaFile(sheet, luaPath, templateContent, config);
                }
            }
        }
Beispiel #19
0
 public static void SetKPRPCConfig(this PwEntry entry, EntryConfig newConfig)
 {
     entry.Strings.Set("KPRPC JSON", new ProtectedString(
         true, Jayrock.Json.Conversion.JsonConvert.ExportToString(newConfig)));
 }
Beispiel #20
0
        // Must match host name; if allowHostnameOnlyMatch is false, exact URL must be matched
        private bool matchesAnyURL(PwEntry pwe, EntryConfig conf, string url, string hostname, bool allowHostnameOnlyMatch)
        {
            string pattern = @"(^|^/|[a-z]+\://)" + System.Text.RegularExpressions.Regex.Escape(hostname) + @"(/|$|\:)";

            // why can url be empty string and still match? removed that option.
            if (pwe.Strings.Exists("URL") && pwe.Strings.ReadSafe("URL").Length > 0
                    && System.Text.RegularExpressions.Regex.IsMatch(pwe.Strings.ReadSafe("URL").ToLower(), pattern)
                    && (allowHostnameOnlyMatch || pwe.Strings.ReadSafe("URL") == url)
               )
                return true;

            if (conf.AltURLs != null)
                foreach (string altURL in conf.AltURLs)
                    if (System.Text.RegularExpressions.Regex.IsMatch(altURL.ToLower(), pattern)
                        && (allowHostnameOnlyMatch || altURL == url))
                        return true;

            return false;
        }
Beispiel #21
0
        public Entry[] FindLogins(string[] URLs, string actionURL, string httpRealm, LoginSearchType lst, bool requireFullURLMatches, 
            string uniqueID, string dbFileName, string freeTextSearch, string username)
        {
            List<PwDatabase> dbs = null;
            int count = 0;
            List<Entry> allEntries = new List<Entry>();

            if (!string.IsNullOrEmpty(dbFileName))
            {
                // find the database
                PwDatabase db = SelectDatabase(dbFileName);
                dbs = new List<PwDatabase>();
                dbs.Add(db);
            }
            else
            {
                // if DB list is not populated, look in all open DBs
                dbs = host.MainWindow.DocumentManager.GetOpenDatabases();
                // unless the DB is the wrong version
                dbs = dbs.FindAll(ConfigIsCorrectVersion);
            }

            //string hostname = URLs[0];
            string actionHost = actionURL;

            // Make sure there is an active database
            if (!ensureDBisOpen()) { return null; }

            // if uniqueID is supplied, match just that one login. if not found, move on to search the content of the logins...
            if (uniqueID != null && uniqueID.Length > 0)
            {
                PwUuid pwuuid = new PwUuid(KeePassLib.Utility.MemUtil.HexStringToByteArray(uniqueID));

                //foreach DB...
                foreach (PwDatabase db in dbs)
                {
                    PwEntry matchedLogin = GetRootPwGroup(db).FindEntry(pwuuid, true);

                    if (matchedLogin == null)
                        continue;

                    Entry[] logins = new Entry[1];
                    logins[0] = (Entry)GetEntryFromPwEntry(matchedLogin, MatchAccuracy.Best, true, db);
                    if (logins[0] != null)
                        return logins;
                }
            }

            if (!string.IsNullOrEmpty(freeTextSearch))
            {
                //foreach DB...
                foreach (PwDatabase db in dbs)
                {
                    KeePassLib.Collections.PwObjectList<PwEntry> output = new KeePassLib.Collections.PwObjectList<PwEntry>();

                    PwGroup searchGroup = GetRootPwGroup(db);
                    //output = searchGroup.GetEntries(true);
                    SearchParameters sp = new SearchParameters();
                    sp.ComparisonMode = StringComparison.InvariantCultureIgnoreCase;
                    sp.SearchString = freeTextSearch;
                    sp.SearchInUserNames = true;
                    sp.SearchInTitles = true;
                    sp.SearchInTags = true;
                    MethodInfo mi;

                    // SearchEntries method signature changed in KP 2.17 so we use
                    // reflection to enable support for both 2.17 and earlier versions
                    try
                    {
                        mi = typeof(PwGroup).GetMethod("SearchEntries", new Type[] { typeof(SearchParameters), typeof(KeePassLib.Collections.PwObjectList<PwEntry>) });
                        mi.Invoke(searchGroup, new object[] { sp, output });
                    }
                    catch (AmbiguousMatchException ex)
                    {
                        // can't find the 2.17 method definition so try for an earlier version
                        mi = typeof(PwGroup).GetMethod("SearchEntries", new Type[] { typeof(SearchParameters), typeof(KeePassLib.Collections.PwObjectList<PwEntry>), typeof(bool) });
                        mi.Invoke(searchGroup, new object[] { sp, output, false });

                        // If an exception is thrown here it would be unexpected and
                        // require a new version of the application to be released
                    }

                    foreach (PwEntry pwe in output)
                    {
                        Entry kpe = (Entry)GetEntryFromPwEntry(pwe, MatchAccuracy.None, true, db);
                        if (kpe != null)
                        {
                            allEntries.Add(kpe);
                            count++;
                        }
                    }
                }

            }
            // else we search for the URLs

            if (count == 0 && URLs.Length > 0 && !string.IsNullOrEmpty(URLs[0]))
            {
                int protocolIndex = -1;
                Dictionary<string, URLSummary> URLHostnameAndPorts = new Dictionary<string, URLSummary>();

                // make sure that hostname and actionURL always represent only the hostname portion
                // of the URL
                // It's tempting to demand that the protocol must match too (e.g. http forms won't
                // match a stored https login) but best not to define such a restriction in KeePassRPC
                // - the RPC client (e.g. KeeFox) can decide to penalise protocol mismatches,
                // potentially dependant on user configuration options in the client.
                for (int i = 0; i < URLs.Length; i++)
                {
                    URLHostnameAndPorts.Add(URLs[i], URLSummary.FromURL(URLs[i]));
                }

                //foreach DB...
                foreach (PwDatabase db in dbs)
                {
                    KeePassLib.Collections.PwObjectList<PwEntry> output = new KeePassLib.Collections.PwObjectList<PwEntry>();

                    PwGroup searchGroup = GetRootPwGroup(db);
                    output = searchGroup.GetEntries(true);
                    List<string> configErrors = new List<string>(1);

                    // Search every entry in the DB
                    foreach (PwEntry pwe in output)
                    {
                        string entryUserName = pwe.Strings.ReadSafe(PwDefs.UserNameField);
                        entryUserName = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(pwe, entryUserName, db);
                        if (EntryIsInRecycleBin(pwe, db))
                            continue; // ignore if it's in the recycle bin

                        //if (string.IsNullOrEmpty(pwe.Strings.ReadSafe("URL")))
                        //    continue; // entries must have a standard URL entry

                        string json = KeePassRPCPlugin.GetPwEntryString(pwe, "KPRPC JSON", db);
                        EntryConfig conf;
                        if (string.IsNullOrEmpty(json))
                        {
                            conf = new EntryConfig();
                        }
                        else
                        {
                            try
                            {
                                conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                            }
                            catch (Exception ex)
                            {
                                configErrors.Add("Username: "******". URL: " + pwe.Strings.ReadSafe("URL"));
                                continue;
                            }
                        }

                        if (conf.Hide)
                            continue;

                        bool entryIsAMatch = false;
                        int bestMatchAccuracy = MatchAccuracy.None;

                        if (conf.RegExURLs != null)
                            foreach (string URL in URLs)
                                foreach (string regexPattern in conf.RegExURLs)
                                {
                                    try
                                    {
                                        if (!string.IsNullOrEmpty(regexPattern) && System.Text.RegularExpressions.Regex.IsMatch(URL, regexPattern))
                                        {
                                            entryIsAMatch = true;
                                            bestMatchAccuracy = MatchAccuracy.Best;
                                            break;
                                        }
                                    }
                                    catch (ArgumentException)
                                    {
                                        MessageBox.Show("'" + regexPattern + "' is not a valid regular expression. This error was found in an entry in your database called '" + pwe.Strings.ReadSafe(PwDefs.TitleField) + "'. You need to fix or delete this regular expression to prevent this warning message appearing.", "Warning: Broken regular expression", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        break;
                                    }
                                }

                        // Check for matching URLs for the page containing the form
                        if (!entryIsAMatch && lst != LoginSearchType.LSTnoForms
                                && (string.IsNullOrEmpty(username) || username == entryUserName))
                        {
                            foreach (string URL in URLs)
                        {

                                int accuracy = bestMatchAccuracyForAnyURL(pwe, conf, URL, URLHostnameAndPorts[URL]);
                                if (accuracy > bestMatchAccuracy)
                                    bestMatchAccuracy = accuracy;

                            }
                        }

                        // Check for matching URLs for the HTTP Auth containing the form
                        if (!entryIsAMatch && lst != LoginSearchType.LSTnoRealms
                                && (string.IsNullOrEmpty(username) || username == entryUserName))

                        {
                            foreach (string URL in URLs)
                            {
                                int accuracy = bestMatchAccuracyForAnyURL(pwe, conf, URL, URLHostnameAndPorts[URL]);
                                if (accuracy > bestMatchAccuracy)
                                    bestMatchAccuracy = accuracy;
                            }
                        }

                        if (bestMatchAccuracy == MatchAccuracy.Best
                            || (!requireFullURLMatches && bestMatchAccuracy > MatchAccuracy.None))
                            entryIsAMatch = true;

                        foreach (string URL in URLs)
                        {
                            // If we think we found a match, check it's not on a block list
                            if (entryIsAMatch && matchesAnyBlockedURL(pwe, conf, URL))
                            {
                                entryIsAMatch = false;
                                break;
                            }
                            if (conf.RegExBlockedURLs != null)
                                foreach (string pattern in conf.RegExBlockedURLs)
                                {
                                    try
                                    {
                                        if (!string.IsNullOrEmpty(pattern) && System.Text.RegularExpressions.Regex.IsMatch(URL, pattern))
                                        {
                                            entryIsAMatch = false;
                                            break;
                                        }
                                    }
                                    catch (ArgumentException)
                                    {
                                        MessageBox.Show("'" + pattern + "' is not a valid regular expression. This error was found in an entry in your database called '" + pwe.Strings.ReadSafe(PwDefs.TitleField) + "'. You need to fix or delete this regular expression to prevent this warning message appearing.", "Warning: Broken regular expression", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        break;
                                    }
                                }
                        }

                        if (entryIsAMatch)
                        {
                            Entry kpe = (Entry)GetEntryFromPwEntry(pwe, bestMatchAccuracy, true, db);
                            if (kpe != null)
                            {
                                allEntries.Add(kpe);
                                count++;
                            }
                        }

                    }
                    if (configErrors.Count > 0)
                        MessageBox.Show("There are configuration errors in your database called '" + db.Name + "'. To fix the entries listed below and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. These entries are affected:" + Environment.NewLine + string.Join(Environment.NewLine, configErrors.ToArray()), "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            allEntries.Sort(delegate(Entry e1, Entry e2)
            {
                return e1.Title.CompareTo(e2.Title);
            });

            return allEntries.ToArray();
        }
        private void AddPasswordBackupLogin(string password, string url)
        {
            if (!host.Database.IsOpen)
                return;

            PwDatabase chosenDB = SelectDatabase("");
            var parentGroup = KeePassRPCPlugin.GetAndInstallKeeFoxPasswordBackupGroup(chosenDB);

            PwEntry newLogin = new PwEntry(true, true);
            newLogin.Strings.Set(PwDefs.TitleField, new ProtectedString(
                chosenDB.MemoryProtection.ProtectTitle, "KeeFox generated password at: " + DateTime.Now));
            newLogin.Strings.Set(PwDefs.UrlField, new ProtectedString(
                chosenDB.MemoryProtection.ProtectUrl, url));
            newLogin.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                chosenDB.MemoryProtection.ProtectPassword, password));
            EntryConfig conf = new EntryConfig();
            conf.BlockDomainOnlyMatch = true;
            conf.Hide = true;
            newLogin.SetKPRPCConfig(conf);
            parentGroup.AddEntry(newLogin, true);

            // We can't save the database at this point because KeePass steals
            // window focus while saving; that breaks Firefox's Australis UI panels.
            host.MainWindow.BeginInvoke(new dlgUpdateUINoSave(updateUINoSave));

            return;
        }
Beispiel #23
0
        private bool UpgradeURLPortEntriesToRetainSubdomainExclusivity(PwDatabase db)
        {
            KeePassLib.Collections.PwObjectList<PwEntry> output;
            output = db.RootGroup.GetEntries(true);

            foreach (PwEntry pwe in output)
            {
                KeePassRPC.DataExchangeModel.EntryConfig conf = null;
                string json = pwe.Strings.ReadSafe("KPRPC JSON");
                if (string.IsNullOrEmpty(json))
                    conf = new EntryConfig();
                else
                {
                    try
                    {
                        conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this.", "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                }

                List<string> URLs = new List<string>();
                if (!string.IsNullOrEmpty(pwe.Strings.ReadSafe("URL")))
                    URLs.Add(pwe.Strings.ReadSafe("URL"));
                if (conf.AltURLs != null)
                    URLs.AddRange(conf.AltURLs);

                foreach (string url in URLs)
                {
                    URLSummary urlsum = URLSummary.FromURL(url);

                    // Require more strict default matching for entries that come
                    // with a port configured (user can override in the rare case
                    // that they want the loose domain-level matching)
                    if (!string.IsNullOrEmpty(urlsum.Port))
                    {
                        conf.BlockDomainOnlyMatch = true;
                        pwe.Strings.Set("KPRPC JSON", new ProtectedString(true, Jayrock.Json.Conversion.JsonConvert.ExportToString(conf)));
                    }
                }
            }

            return true;
        }
Beispiel #24
0
 // hostname-wide blocks are not natively supported but can be emulated using an appropriate regex
 private bool matchesAnyBlockedURL(PwEntry pwe, EntryConfig conf, string url)
 {
     if (conf.BlockedURLs != null)
         foreach (string altURL in conf.BlockedURLs)
             if (altURL.Contains(url))
                 return true;
     return false;
 }
Beispiel #25
0
        private LightEntry GetEntryFromPwEntry(PwEntry pwe, EntryConfig conf, int matchAccuracy, bool fullDetails, PwDatabase db, bool abortIfHidden)
        {
            ArrayList formFieldList = new ArrayList();
            ArrayList URLs = new ArrayList();
            URLs.Add(pwe.Strings.ReadSafe("URL"));
            bool usernameFound = false;
            bool passwordFound = false;
            bool alwaysAutoFill = false;
            bool neverAutoFill = false;
            bool alwaysAutoSubmit = false;
            bool neverAutoSubmit = false;
            int priority = 0;
            string usernameName = "";
            string usernameValue = "";

            if (abortIfHidden && conf.Hide)
                return null;

            if (!fullDetails)
            {

            }
            else
            {
                if (conf.FormFieldList != null)
                {
                    foreach (FormField ff in conf.FormFieldList)
                    {
                        if (ff.Type == FormFieldType.FFTpassword)
                        {
                            string ffValue = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(pwe, ff.Value, db);
                            if (!string.IsNullOrEmpty(ffValue))
                            {
                                formFieldList.Add(new FormField(ff.Name, "KeePass password", ffValue, ff.Type, ff.Id, ff.Page));
                                passwordFound = true;
                            }
                        }
                        else if (ff.Type == FormFieldType.FFTusername)
                        {
                            string ffValue = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(pwe, ff.Value, db);
                            if (!string.IsNullOrEmpty(ffValue))
                            {
                                formFieldList.Add(new FormField(ff.Name, "KeePass username", ffValue, ff.Type, ff.Id, ff.Page));
                                usernameFound = true;
                            }
                        }
                        else
                            formFieldList.Add(new FormField(ff.Name, ff.Name, ff.Value, ff.Type, ff.Id, ff.Page));
                    }
                }
            }
            if (conf.AltURLs != null)
                URLs.AddRange(conf.AltURLs);

            // If we didn't find an explicit password field, we assume any value
            // in the KeePass "password" box is what we are looking for
            if (fullDetails && !passwordFound)
            {
                string ffValue = KeePassRPCPlugin.GetPwEntryString(pwe, "Password", db);
                ffValue = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(pwe, ffValue, db);
                if (!string.IsNullOrEmpty(ffValue))
                {
                    formFieldList.Add(new FormField("password",
                        "KeePass password", ffValue, FormFieldType.FFTpassword, "password", 1));
                }
            }

            // If we didn't find an explicit username field, we assume any value
            // in the KeePass "username" box is what we are looking for
            if (!usernameFound)
            {
                string ffValue = KeePassRPCPlugin.GetPwEntryString(pwe, "UserName", db);
                ffValue = KeePassRPCPlugin.GetPwEntryStringFromDereferencableValue(pwe, ffValue, db);
                if (!string.IsNullOrEmpty(ffValue))
                {
                    formFieldList.Add(new FormField("username",
                        "KeePass username", ffValue, FormFieldType.FFTusername, "username", 1));
                    usernameName = "username";
                    usernameValue = ffValue;
                }
            }

            string imageData = iconToBase64(pwe.CustomIconUuid, pwe.IconId);
            //Debug.WriteLine("GetEntryFromPwEntry icon converted: " + sw.Elapsed);

            if (fullDetails)
            {
                alwaysAutoFill = conf.AlwaysAutoFill;
                alwaysAutoSubmit = conf.AlwaysAutoSubmit;
                neverAutoFill = conf.NeverAutoFill;
                neverAutoSubmit = conf.NeverAutoSubmit;
                priority = conf.Priority;

            }

            //sw.Stop();
            //Debug.WriteLine("GetEntryFromPwEntry execution time: " + sw.Elapsed);
            //Debug.Unindent();

            if (fullDetails)
            {
                string realm = "";
                if (!string.IsNullOrEmpty(conf.HTTPRealm))
                    realm = conf.HTTPRealm;

                FormField[] temp = (FormField[])formFieldList.ToArray(typeof(FormField));
                Entry kpe = new Entry(
                (string[])URLs.ToArray(typeof(string)), realm,
                pwe.Strings.ReadSafe(PwDefs.TitleField), temp,
                KeePassLib.Utility.MemUtil.ByteArrayToHexString(pwe.Uuid.UuidBytes),
                alwaysAutoFill, neverAutoFill, alwaysAutoSubmit, neverAutoSubmit, priority,
                GetGroupFromPwGroup(pwe.ParentGroup), imageData,
                GetDatabaseFromPwDatabase(db, false, true),matchAccuracy);
                return kpe;
            }
            else
            {
                return new LightEntry((string[])URLs.ToArray(typeof(string)),
                    pwe.Strings.ReadSafe(PwDefs.TitleField),
                    KeePassLib.Utility.MemUtil.ByteArrayToHexString(pwe.Uuid.UuidBytes),
                    imageData, usernameName, usernameValue);
            }
        }
Beispiel #26
0
 public static string WriteToLua(WDBSheet sheet, string templateContent, EntryConfig config = null)
 {
     string[] assemblyNames = new string[] { typeof(WDBSheet).Assembly.Location };
     return(WriteToLua(sheet, templateContent, assemblyNames, config ?? EntryConfig.Default));
 }
Beispiel #27
0
        private void InstallKeeFoxSampleEntries(PwDatabase pd, bool skipGroupWarning)
        {
            PwGroup kfpg = GetAndInstallKeeFoxGroup(pd, skipGroupWarning);
            if (kfpg == null)
                return;

            List<PwUuid> pwuuids = GetKeeFoxTutorialUUIDs();
            bool entryAdded = false;

            // We search for the KeeFox entries in the entire database 
            // in case the user has moved them out of the KeeFox group

            if (pd.RootGroup.FindEntry(pwuuids[0], true) == null)
            {
                PwEntry pe = createKeeFoxSample(pd, pwuuids[0],
                    "Quick Start (double click on the URL to learn how to use KeeFox)",
                    "testU1", "testP1", @"http://tutorial.keefox.org/", null);
                EntryConfig conf = new EntryConfig();
                conf.BlockDomainOnlyMatch = true;
                pe.SetKPRPCConfig(conf);
                kfpg.AddEntry(pe, true);
                entryAdded = true;
            }

            if (pd.RootGroup.FindEntry(pwuuids[1], true) == null)
            {
                PwEntry pe = createKeeFoxSample(pd, pwuuids[1],
                    "KeeFox sample entry with alternative URL",
                    "testU2", "testP2", @"http://does.not.exist/", @"This sample helps demonstrate the use of alternative URLs to control which websites each password entry should apply to.");
                EntryConfig conf = new EntryConfig();
                conf.Version = 1;
                conf.AltURLs = new string[] { @"http://tutorial-section-c.keefox.org/part3" };
                conf.BlockDomainOnlyMatch = true;
                pe.SetKPRPCConfig(conf);
                kfpg.AddEntry(pe, true);
                entryAdded = true;
            }

            if (pd.RootGroup.FindEntry(pwuuids[2], true) == null)
            {
                PwEntry pe = createKeeFoxSample(pd, pwuuids[2],
                    "KeeFox sample entry with no auto-fill and no auto-submit",
                    "testU3", "testP3", @"http://tutorial-section-d.keefox.org/part4", @"This sample helps demonstrate the use of advanced settings that give you fine control over the behaviour of a password entry. In this specific example, the entry has been set to never automatically fill matching login forms when the web page loads and to never automatically submit, even when you have explicity told KeeFox to log in to this web page.");
                EntryConfig conf = new EntryConfig();
                conf.Version = 1;
                conf.NeverAutoFill = true;
                conf.NeverAutoSubmit = true;
                conf.BlockDomainOnlyMatch = true;
                pe.SetKPRPCConfig(conf);
                kfpg.AddEntry(pe, true);
                entryAdded = true;
            }

            if (pd.RootGroup.FindEntry(pwuuids[4], true) == null)
            {
                PwEntry pe = createKeeFoxSample(pd, pwuuids[4],
                    "KeeFox sample entry for HTTP authentication",
                    "testU4", "testP4", @"http://tutorial-section-d.keefox.org/part6", @"This sample helps demonstrate logging in to HTTP authenticated websites.");
                EntryConfig conf = new EntryConfig();
                conf.Version = 1;
                conf.HTTPRealm = "KeeFox tutorial sample";
                conf.BlockDomainOnlyMatch = true;
                pe.SetKPRPCConfig(conf);
                kfpg.AddEntry(pe, true);
                entryAdded = true;
            }

            if (entryAdded)
                _host.MainWindow.UpdateUI(true, null, true, null, true, null, true);
        }
 private void UpdateKPRPCJSON(EntryConfig _conf)
 {
     // if the config is identical to an empty (default) config, only update if a JSON string already exists
     if (!_conf.Equals(new EntryConfig()) || _strings.GetKeys().Contains("KPRPC JSON"))
         changeAdvancedString("KPRPC JSON", Jayrock.Json.Conversion.JsonConvert.ExportToString(_conf), true);
 }
Beispiel #29
0
 private void FileToFile(EntryConfig entry)
 {
     Log.Information($"Copying file {entry.SourceFile} to {entry.DestinationFile} ...");
     File.Copy(entry.SourceFile, entry.DestinationFile, true);
 }
Beispiel #30
0
        private bool UpgradeKeeFoxTutorialEntriesToRetainSubdomainExclusivityAndResetPriority(PwDatabase db)
        {
            // The KeeFox tutorial relies on subdomains being seen as independent
            // websites but that is no longer the default behaviour in KeeFox 1.5+
            // so we have to adjust any existing entries so that the tutorial
            // continues to work for users with existing databases.

            List<string> uuids = GetKeeFoxTutorialUUIDsAsStrings();

            KeePassLib.Collections.PwObjectList<PwEntry> output = new KeePassLib.Collections.PwObjectList<PwEntry>();

            // Scan every entry for matching UUIDs and add them to the list for upgrade
            KeePassLib.Delegates.EntryHandler eh = delegate(PwEntry pe)
            {
                if (uuids.Contains(pe.Uuid.ToHexString()))
                {
                    output.Add(pe);
                }
                return true;
            };
            db.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh);

            if (output.UCount > 0)
            {
                foreach (PwEntry pwe in output)
                {
                    KeePassRPC.DataExchangeModel.EntryConfig conf = null;
                    string json = pwe.Strings.ReadSafe("KPRPC JSON");
                    if (string.IsNullOrEmpty(json))
                        conf = new EntryConfig();
                    else
                    {
                        try
                        {
                            conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this.", "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }

                    conf.BlockDomainOnlyMatch = true;
                    conf.Priority = 0;
                    pwe.Strings.Set("KPRPC JSON", new ProtectedString(true, Jayrock.Json.Conversion.JsonConvert.ExportToString(conf)));
                }
                return true;
            }
            return true;
        }
Beispiel #31
0
        private void MergeEntries(PwEntry destination, PwEntry source, int urlMergeMode, PwDatabase db)
        {
            EntryConfig destConfig;
            string destJSON = KeePassRPCPlugin.GetPwEntryString(destination, "KPRPC JSON", db);
            if (string.IsNullOrEmpty(destJSON))
            {
                destConfig = new EntryConfig();
            }
            else
            {
                try
                {
                    destConfig = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), destJSON);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + destination.Strings.ReadSafe("URL") + " and the full configuration data is: " + destJSON, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            EntryConfig sourceConfig;
            string sourceJSON = KeePassRPCPlugin.GetPwEntryString(source, "KPRPC JSON", db);
            if (string.IsNullOrEmpty(sourceJSON))
            {
                sourceConfig = new EntryConfig();
            }
            else
            {
                try
                {
                    sourceConfig = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), sourceJSON);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + source.Strings.ReadSafe("URL") + " and the full configuration data is: " + sourceJSON, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            destination.CreateBackup(db);

            destConfig.HTTPRealm = sourceConfig.HTTPRealm;
            destination.IconId = source.IconId;
            destination.CustomIconUuid = source.CustomIconUuid;
            destination.Strings.Set("UserName", new ProtectedString(
                host.Database.MemoryProtection.ProtectUserName, source.Strings.ReadSafe("UserName")));
            destination.Strings.Set("Password", new ProtectedString(
                host.Database.MemoryProtection.ProtectPassword, source.Strings.ReadSafe("Password")));
            destConfig.FormFieldList = sourceConfig.FormFieldList;

            // This algorithm could probably be made more efficient (lots of O(n) operations
            // but we're dealing with pretty small n so I've gone with the conceptually
            // easiest approach for now).

            List<string> destURLs = new List<string>();
            destURLs.Add(destination.Strings.ReadSafe("URL"));
            if (destConfig.AltURLs != null)
                destURLs.AddRange(destConfig.AltURLs);

            List<string> sourceURLs = new List<string>();
            sourceURLs.Add(source.Strings.ReadSafe("URL"));
            if (sourceConfig.AltURLs != null)
                sourceURLs.AddRange(sourceConfig.AltURLs);

            switch (urlMergeMode)
            {
                case 1:
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 2:
                    destURLs.RemoveAt(0);
                    MergeInNewURLs(destURLs, sourceURLs);
                    break;
                case 3:
                    if (sourceURLs.Count > 0)
                    {
                        foreach (string sourceUrl in sourceURLs)
                            if (!destURLs.Contains(sourceUrl))
                                destURLs.Add(sourceUrl);
                    }
                    break;
                case 4:
                default:
                    // No changes to URLs
                    break;
            }

            // These might not have changed but meh
            destination.Strings.Set("URL", new ProtectedString(host.Database.MemoryProtection.ProtectUrl, destURLs[0]));
            destConfig.AltURLs = new string[0];
            if (destURLs.Count > 1)
                destConfig.AltURLs = destURLs.GetRange(1,destURLs.Count-1).ToArray();

            destination.Strings.Set("KPRPC JSON", new ProtectedString(true, Jayrock.Json.Conversion.JsonConvert.ExportToString(destConfig)));
            destination.Touch(true);
        }
Beispiel #32
0
        private void setPwEntryFromEntry(PwEntry pwe, Entry login)
        {
            bool firstPasswordFound = false;
            EntryConfig conf = new EntryConfig();
            List<FormField> ffl = new List<FormField>();

            // Go through each form field, mostly just making a copy but with occasional tweaks such as default username and password selection
            // by convention, we'll always have the first text field as the username when both reading and writing from the EntryConfig
            foreach (FormField kpff in login.FormFieldList)
            {
                if (kpff.Type == FormFieldType.FFTpassword && !firstPasswordFound)
                {
                    ffl.Add(new FormField(kpff.Name, "KeePass password", "{PASSWORD}", kpff.Type, kpff.Id, kpff.Page));
                    pwe.Strings.Set("Password", new ProtectedString(host.Database.MemoryProtection.ProtectPassword, kpff.Value));
                    firstPasswordFound = true;
                }
                else if (kpff.Type == FormFieldType.FFTusername)
                {
                    ffl.Add(new FormField(kpff.Name, "KeePass username", "{USERNAME}", kpff.Type, kpff.Id, kpff.Page));
                    pwe.Strings.Set("UserName", new ProtectedString(host.Database.MemoryProtection.ProtectUserName, kpff.Value));
                }
                else
                {
                    ffl.Add(new FormField(kpff.Name, kpff.Name, kpff.Value, kpff.Type, kpff.Id, kpff.Page));
                }
            }
            conf.FormFieldList = ffl.ToArray();

            List<string> altURLs = new List<string>();

            for (int i = 0; i < login.URLs.Length; i++)
            {
                string url = login.URLs[i];
                if (i == 0)
                {
                    URLSummary urlsum = URLSummary.FromURL(url);

                    // Require more strict default matching for entries that come
                    // with a port configured (user can override in the rare case
                    // that they want the loose domain-level matching)
                    if (!string.IsNullOrEmpty(urlsum.Port))
                        conf.BlockDomainOnlyMatch = true;

                    pwe.Strings.Set("URL", new ProtectedString(host.Database.MemoryProtection.ProtectUrl, url ?? ""));
                }
                else
                    altURLs.Add(url);
            }
            conf.AltURLs = altURLs.ToArray();
            conf.HTTPRealm = login.HTTPRealm;
            conf.Version = 1;

            // Set some of the string fields
            pwe.Strings.Set(PwDefs.TitleField, new ProtectedString(host.Database.MemoryProtection.ProtectTitle, login.Title ?? ""));

            // update the icon for this entry (in most cases we'll
            // just detect that it is the same standard icon as before)
            PwUuid customIconUUID = PwUuid.Zero;
            PwIcon iconId = PwIcon.Key;
            if (login.IconImageData != null
                && login.IconImageData.Length > 0
                && base64ToIcon(login.IconImageData, ref customIconUUID, ref iconId))
            {
                if (customIconUUID == PwUuid.Zero)
                    pwe.IconId = iconId;
                else
                    pwe.CustomIconUuid = customIconUUID;
            }

            pwe.Strings.Set("KPRPC JSON", new ProtectedString(true, Jayrock.Json.Conversion.JsonConvert.ExportToString(conf)));
        }
 private bool matchesAnyBlockedURL(PwEntry pwe, EntryConfig conf, string url) // hostname-wide blocks are not natively supported but can be emulated using an appropriate regex
 {
     if (conf.BlockedURLs != null)
         foreach (string altURL in conf.BlockedURLs)
             if (altURL.Contains(url))
                 return true;
     return false;
 }
Beispiel #34
0
        private void ConvertKPRPCSeperateStringsToJSON(PwEntry pwe, PwDatabase db)
        {
            //Sanity check to protect against duplicate updates
            if (pwe.Strings.Exists("KPRPC JSON"))
                return;

            ArrayList formFieldList = new ArrayList();
            ArrayList URLs = new ArrayList();
            //bool usernameFound = false;
            bool passwordFound = false;
            bool alwaysAutoFill = false;
            bool neverAutoFill = false;
            bool alwaysAutoSubmit = false;
            bool neverAutoSubmit = false;
            int priority = 0;
            string usernameName = "";
            string usernameValue = "";


            foreach (System.Collections.Generic.KeyValuePair
                <string, KeePassLib.Security.ProtectedString> pwestring in pwe.Strings)
            {
                string pweKey = pwestring.Key;
                string pweValue = pwestring.Value.ReadString();

                if ((pweKey.StartsWith("Form field ") || pweKey.StartsWith("KPRPC Form field ")) && pweKey.EndsWith(" type") && pweKey.Length > 16)
                {
                    string fieldName = "";
                    if (pweKey.StartsWith("Form field "))
                        fieldName = pweKey.Substring(11).Substring(0, pweKey.Length - 11 - 5);
                    else
                        fieldName = pweKey.Substring(17).Substring(0, pweKey.Length - 17 - 5);

                    string fieldId = "";
                    int fieldPage = 1;

                    if (pwe.Strings.Exists("Form field " + fieldName + " page"))
                    {
                        try
                        {
                            fieldPage = int.Parse(GetPwEntryString(pwe, "Form field " + fieldName + " page", db));
                        }
                        catch (Exception)
                        {
                            fieldPage = 1;
                        }
                    }
                    else if (pwe.Strings.Exists("KPRPC Form field " + fieldName + " page"))
                    {
                        try
                        {
                            fieldPage = int.Parse(GetPwEntryString(pwe, "KPRPC Form field " + fieldName + " page", db));
                        }
                        catch (Exception)
                        {
                            fieldPage = 1;
                        }
                    }

                    if (pwe.Strings.Exists("Form field " + fieldName + " id"))
                        fieldId = GetPwEntryString(pwe, "Form field " + fieldName + " id", db);
                    else if (pwe.Strings.Exists("KPRPC Form field " + fieldName + " id"))
                        fieldId = GetPwEntryString(pwe, "KPRPC Form field " + fieldName + " id", db);

                    //Not going to backfill missing passwords and usernames but we do need to convert from old value placeholder to new one
                    if (pweValue == "password")
                    {
                        if (pwe.Strings.Exists("Form field " + fieldName + " value"))
                            formFieldList.Add(new FormField(fieldName,
                                fieldName, GetPwEntryString(pwe, "Form field " + fieldName + " value", db), FormFieldType.FFTpassword, fieldId, fieldPage));
                        else if (pwe.Strings.Exists("KPRPC Form field " + fieldName + " value"))
                            formFieldList.Add(new FormField(fieldName,
                                fieldName, GetPwEntryString(pwe, "KPRPC Form field " + fieldName + " value", db), FormFieldType.FFTpassword, fieldId, fieldPage));
                        else if (!passwordFound) // it's the default password
                        {
                            formFieldList.Add(new FormField(fieldName,
                                "KeePass password", "{PASSWORD}", FormFieldType.FFTpassword, fieldId, fieldPage));
                            passwordFound = true;
                        }
                    }
                    else if (pweValue == "username")
                    {
                        string displayUser = "******";
                        //if (usernameFound)
                        //    displayUser = fieldName;
                        formFieldList.Add(new FormField(fieldName,
                            displayUser, "{USERNAME}", FormFieldType.FFTusername, fieldId, fieldPage));
                        usernameName = fieldName;
                        usernameValue = GetPwEntryString(pwe, "UserName", db);
                        //usernameFound = true;
                    }
                    else if (pweValue == "text")
                    {
                        formFieldList.Add(new FormField(fieldName,
                fieldName, GetFormFieldValue(pwe, fieldName, db), FormFieldType.FFTtext, fieldId, fieldPage));
                    }
                    else if (pweValue == "radio")
                    {
                        formFieldList.Add(new FormField(fieldName,
                fieldName, GetFormFieldValue(pwe, fieldName, db), FormFieldType.FFTradio, fieldId, fieldPage));
                    }
                    else if (pweValue == "select")
                    {
                        formFieldList.Add(new FormField(fieldName,
                fieldName, GetFormFieldValue(pwe, fieldName, db), FormFieldType.FFTselect, fieldId, fieldPage));
                    }
                    else if (pweValue == "checkbox")
                    {
                        formFieldList.Add(new FormField(fieldName,
                fieldName, GetFormFieldValue(pwe, fieldName, db), FormFieldType.FFTcheckbox, fieldId, fieldPage));
                    }
                }
                else if (pweKey == "Alternative URLs" || pweKey == "KPRPC Alternative URLs")
                {
                    string[] urlsArray = pweValue.Split(new char[] { ' ' });
                    foreach (string altURL in urlsArray)
                        if (!string.IsNullOrEmpty(altURL)) URLs.Add(altURL);

                }
            }

            if (pwe.Strings.Exists("KeeFox Always Auto Fill") || pwe.Strings.Exists("KPRPC Always Auto Fill"))
                alwaysAutoFill = true;
            if (pwe.Strings.Exists("KeeFox Always Auto Submit") || pwe.Strings.Exists("KPRPC Always Auto Submit"))
                alwaysAutoSubmit = true;
            if (pwe.Strings.Exists("KeeFox Never Auto Fill") || pwe.Strings.Exists("KPRPC Never Auto Fill"))
                neverAutoFill = true;
            if (pwe.Strings.Exists("KeeFox Never Auto Submit") || pwe.Strings.Exists("KPRPC Never Auto Submit"))
                neverAutoSubmit = true;

            if (pwe.Strings.Exists("KeeFox Priority"))
            {
                string priorityString = pwe.Strings.ReadSafe("KeeFox Priority");
                if (!string.IsNullOrEmpty(priorityString))
                {
                    try
                    {
                        priority = int.Parse(priorityString);
                    }
                    catch
                    { }

                    if (priority < 0 || priority > 100000)
                        priority = 0;
                }
            }
            if (pwe.Strings.Exists("KPRPC Priority"))
            {
                string priorityString = pwe.Strings.ReadSafe("KPRPC Priority");
                if (!string.IsNullOrEmpty(priorityString))
                {
                    try
                    {
                        priority = int.Parse(priorityString);
                    }
                    catch
                    { }

                    if (priority < 0 || priority > 100000)
                        priority = 0;
                }
            }

            string realm = "";
            try
            {
                realm = GetPwEntryString(pwe, "Form HTTP realm", db);
            }
            catch (Exception) { realm = ""; }
            if (string.IsNullOrEmpty(realm))
            {
                try
                {
                    realm = GetPwEntryString(pwe, "KPRPC Form HTTP realm", db);
                }
                catch (Exception) { realm = ""; }
            }
            if (string.IsNullOrEmpty(realm))
            {
                try
                {
                    realm = GetPwEntryString(pwe, "KPRPC HTTP realm", db);
                }
                catch (Exception) { realm = ""; }
            }


            EntryConfig conf = new EntryConfig();
            conf.Hide = false;
            string hide = "";
            try
            {
                hide = GetPwEntryString(pwe, "Hide from KeeFox", db);
                if (!string.IsNullOrEmpty(hide))
                    conf.Hide = true;
            }
            catch (Exception) { hide = ""; }
            if (string.IsNullOrEmpty(hide))
            {
                try
                {
                    hide = GetPwEntryString(pwe, "Hide from KPRPC", db);
                    if (!string.IsNullOrEmpty(hide))
                        conf.Hide = true;
                }
                catch (Exception) { hide = ""; }
            }

            conf.BlockHostnameOnlyMatch = false;
            string block = "";
            try
            {
                block = GetPwEntryString(pwe, "KPRPC Block hostname-only match", db);
                if (!string.IsNullOrEmpty(block))
                    conf.BlockHostnameOnlyMatch = true;
            }
            catch (Exception) { block = ""; }


            FormField[] temp = (FormField[])formFieldList.ToArray(typeof(FormField));

            conf.AltURLs = (string[])URLs.ToArray(typeof(string));

            try
            {
                List<string> listNormalBlockedURLs = new List<string>();
                string urls = GetPwEntryString(pwe, "KPRPC Blocked URLs", db);
                foreach (string url in urls.Split(' '))
                    if (!string.IsNullOrEmpty(url)) listNormalBlockedURLs.Add(url);
                conf.BlockedURLs = listNormalBlockedURLs.ToArray();
            }
            catch (Exception) { }

            try
            {
                List<string> listRegExURLs = new List<string>();
                string urls = GetPwEntryString(pwe, "KPRPC URL Regex match", db);
                foreach (string url in urls.Split(' '))
                    if (!string.IsNullOrEmpty(url)) listRegExURLs.Add(url);
                conf.RegExURLs = listRegExURLs.ToArray();
            }
            catch (Exception) { }

            try
            {
                List<string> listRegExBlockedURLs = new List<string>();
                string urls = GetPwEntryString(pwe, "KPRPC URL Regex block", db);
                foreach (string url in urls.Split(' '))
                    if (!string.IsNullOrEmpty(url)) listRegExBlockedURLs.Add(url);
                conf.RegExBlockedURLs = listRegExBlockedURLs.ToArray();
            }
            catch (Exception) { }


            conf.AlwaysAutoFill = alwaysAutoFill;
            conf.AlwaysAutoSubmit = alwaysAutoSubmit;
            conf.FormActionURL = GetPwEntryString(pwe, "Form match URL", db);
            conf.FormFieldList = temp;
            conf.HTTPRealm = realm;
            conf.NeverAutoFill = neverAutoFill;
            conf.NeverAutoSubmit = neverAutoSubmit;
            conf.Priority = priority;
            conf.Version = 1;

            // Store the new config info
            pwe.SetKPRPCConfig(conf);

            // Delete all old advanced strings...

            List<string> advancedStringKeysToDelete = new List<string>();

            foreach (KeyValuePair<string, ProtectedString> kvp in pwe.Strings)
            {
                if (StringIsFromKPRPCv1(kvp.Key))
                {
                    // Not sure how kindly KeePass would take to DB changes while iterating so we'll store a list for later
                    advancedStringKeysToDelete.Add(kvp.Key);
                }
            }

            foreach (string item in advancedStringKeysToDelete)
            {
                pwe.Strings.Remove(item);
            }
        }
Beispiel #35
0
 public static void SetKPRPCConfig(this PwEntry entry, EntryConfig newConfig)
 {
     entry.Strings.Set("KPRPC JSON", new ProtectedString(
                           true, Jayrock.Json.Conversion.JsonConvert.ExportToString(newConfig)));
 }
Beispiel #36
0
        public static void WriteToLuaFile(WDBSheet sheet, string filePath, string templateContent, EntryConfig config = null)
        {
            string content = WriteToLua(sheet, templateContent, config);

            if (string.IsNullOrEmpty(content))
            {
                throw new Exception("");
            }

            File.WriteAllText(filePath, content);
        }
Beispiel #37
0
        // Must match host name; if allowHostnameOnlyMatch is false, exact URL must be matched
        private int bestMatchAccuracyForAnyURL(PwEntry pwe, EntryConfig conf, string url, URLSummary urlSummary)
        {
            bool requireExactURLMatch = conf.BlockHostnameOnlyMatch;
            bool requireAtLeastHostnameAndPortURLMatch = conf.BlockDomainOnlyMatch;

            int bestMatchSoFar = MatchAccuracy.None;

            List<string> URLs = new List<string>(3);
            URLs.Add(pwe.Strings.ReadSafe("URL"));
            if (conf.AltURLs != null)
                URLs.AddRange(conf.AltURLs);

            foreach (string entryURL in URLs)
            {
                if (entryURL == url)
                    return MatchAccuracy.Best;

                // If we require very accurate matches, we can skip the more complex assessment below
                if (requireExactURLMatch)
                    continue;

                int entryUrlQSStartIndex = entryURL.IndexOf('?');
                int urlQSStartIndex = url.IndexOf('?');
                string entryUrlExcludingQS = entryURL.Substring(0,
                    entryUrlQSStartIndex > 0 ? entryUrlQSStartIndex : entryURL.Length);
                string urlExcludingQS = url.Substring(0,
                    urlQSStartIndex > 0 ? urlQSStartIndex : url.Length);
                if (entryUrlExcludingQS == urlExcludingQS)
                    return MatchAccuracy.Close;

                // If we've already found a reasonable match, we can skip the rest of the assessment for subsequent URLs
                // apart from the check for matches against a hostname excluding query string
                if (bestMatchSoFar >= MatchAccuracy.HostnameAndPort)
                    continue;

                URLSummary entryUrlSummary = URLSummary.FromURL(entryURL);

                if (entryUrlSummary.HostnameAndPort == urlSummary.HostnameAndPort)
                    bestMatchSoFar = MatchAccuracy.HostnameAndPort;

                // If we need at least a matching hostname and port (equivelent to
                // KeeFox <1.5) or we are missing the information needed to match
                // more loose components of the URL we have to skip these last tests
                if (requireAtLeastHostnameAndPortURLMatch || entryUrlSummary.Domain == null || urlSummary.Domain == null)
                    continue;

                if (bestMatchSoFar < MatchAccuracy.Hostname
                    && entryUrlSummary.Domain.Hostname == urlSummary.Domain.Hostname)
                    bestMatchSoFar = MatchAccuracy.Hostname;

                if (bestMatchSoFar < MatchAccuracy.Domain
                    && entryUrlSummary.Domain.RegistrableDomain == urlSummary.Domain.RegistrableDomain)
                    bestMatchSoFar = MatchAccuracy.Domain;
            }
            return bestMatchSoFar;
        }
Beispiel #38
0
        private static string WriteToLua(WDBSheet sheet, string templateContent, string[] assemblyNames, EntryConfig config)
        {
            StringContextContainer context = new StringContextContainer();

            context.Add("__sheet__", sheet);
            string content = TemplateEngine.Generate(context, templateContent, assemblyNames, config);

            context.Remove("__sheet__");
            return(content);
        }
Beispiel #39
0
        private LightEntry GetEntryFromPwEntry(PwEntry pwe, int matchAccuracy, bool fullDetails, PwDatabase db, bool abortIfHidden)
        {
            string json = KeePassRPCPlugin.GetPwEntryString(pwe, "KPRPC JSON", db);

            EntryConfig conf;
            if (string.IsNullOrEmpty(json))
                conf = new EntryConfig();
            else
            {
                try
                {
                    conf = (EntryConfig)Jayrock.Json.Conversion.JsonConvert.Import(typeof(EntryConfig), json);
                }
                catch (Exception)
                {
                    MessageBox.Show("There are configuration errors in this entry. To fix the entry and prevent this warning message appearing, please edit the value of the 'KeePassRPC JSON config' advanced string. Please ask for help on http://keefox.org/help/forum if you're not sure how to fix this. The URL of the entry is: " + pwe.Strings.ReadSafe("URL") + " and the full configuration data is: " + json, "Warning: Configuration errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }
            }
            return GetEntryFromPwEntry(pwe, conf, matchAccuracy, fullDetails, db, abortIfHidden);
        }