Devin Martin avatar Devin Martin committed 7882d1c

Allow credentials for a URL to be stored in the KeePass database for synchronization.

Comments (0)

Files changed (8)

KeeCloud/KeeCloud.csproj

     <Compile Include="StandardProtectedStrings.cs" />
     <Compile Include="Utilities\AsyncOperationWithSynchronizationContext.cs" />
     <Compile Include="Utilities\DatabaseHelpers.cs" />
+    <Compile Include="WebRequests\EntryCredentials.cs" />
     <Compile Include="WebRequests\SuccessWebResponse.cs" />
     <Compile Include="WebRequests\ProviderWebRequest.cs" />
     <Compile Include="Providers\Dropbox\DropboxProvider.cs" />

KeeCloud/KeeCloudFileExt.cs

         public override bool Initialize(IPluginHost host)
         {
 #if DEVELOPING
+            // Obviously you can attatch directly to the KeePass process from Visual Studio as well if you prefer
             try
             {
                 if (!Debugger.IsAttached)
 
             this.wizardItem = host.MainWindow.ToolsMenu.DropDown.Items.Add("URL Credential Wizard", Resource1.key_go, (sender, e) => this.LaunchWizard());
 
-            ProviderRegistry.RegisterAllIFRequired();
+            ProviderRegistry.RegisterAllWithContext(host);
             return true;
         }
 

KeeCloud/ProviderRegistry.cs

 using KeeCloud.WebRequests;
+using KeePass.Plugins;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 {
     public class ProviderRegistry
     {
-        static readonly object registrationSync = new object();
-        static bool isRegistered = false;
-
         public static IEnumerable<ProviderItem> SupportedWebRequests
         {
             get
         /// <summary>
         /// Register all supported prefixes with the .net framework
         /// </summary>
-        public static void RegisterAllIFRequired()
+        public static void RegisterAllWithContext(IPluginHost host)
         {
-            lock (registrationSync)
+            var creator = new ProviderWebRequestCreator(host);
+            foreach (var supported in SupportedWebRequests)
             {
-                if (!isRegistered)
-                {
-                    isRegistered = true;
-                    foreach (var supported in SupportedWebRequests)
-                    {
-                        ProviderWebRequest.RegisterPrefix(supported.Protocol + ":", ProviderWebRequestCreator.Instance);
-                    }
-                }
+                ProviderWebRequest.RegisterPrefix(supported.Protocol + ":", creator);
             }
         }
 

KeeCloud/Providers/Dropbox/Api.cs

         /// <summary>
         /// This is the App key provided by Dropbox
         /// </summary>
-        const string appKey = "dummy";
+        const string appKey = "lmtap1z523irkms";
         /// <summary>
         /// This is the App secret provided by Dropbox
         /// </summary>
-        const string appSecret = "dummy";
+        const string appSecret = "2v9k5xze6f9r0ua";
 
         public static DropNetClient Client
         {

KeeCloud/Utilities/DatabaseHelpers.cs

 using KeePassLib;
 using System;
 using System.Collections.Generic;
+using System.Linq;
 
 namespace KeeCloud.Utilities
 {
     {
         public static IEnumerable<PwGroup> GetAllGroups(this PwDatabase database)
         {
-            return Flatten(database.RootGroup, _ => _.Groups);
+            return Flatten<PwGroup>(database.RootGroup, _ => _.Groups);
+        }
+
+        public static IEnumerable<PwEntry> GetAllPasswords(this PwDatabase database)
+        {
+            return from g in database.GetAllGroups()
+                   from pe in g.Entries
+                   select pe;
         }
 
         public static IEnumerable<T> Flatten<T>(T node, Func<T, IEnumerable<T>> getSubEnumerable)
         {
             yield return node;
-
             if (getSubEnumerable != null)
             {
                 foreach (var subNode in getSubEnumerable(node))
                     yield return subNode;
             }
         }
+
+        public static bool EntryStringEquals(this PwEntry entry, string key, string expectedValue)
+        {
+            return entry.EntryStringExistsAndContidtionMet(key, value =>
+            {
+                return value.Equals(expectedValue, StringComparison.InvariantCultureIgnoreCase);
+            });
+        }
+
+        public static bool EntryStringNotNullOrEmpty(this PwEntry entry, string key)
+        {
+            return entry.EntryStringExistsAndContidtionMet(key, value => !string.IsNullOrEmpty(value));
+        }
+
+        public static bool EntryStringExistsAndContidtionMet(this PwEntry entry, string key, Func<string, bool> expectation)
+        {
+            if (expectation == null)
+                return false;
+            else
+            {
+                var value = entry.Strings.Get(key);
+                if (value != null && !value.IsEmpty)
+                {
+                    var rawValue = value.ReadString();
+                    return expectation(rawValue);
+                }
+                else
+                    return false;
+            }
+        }
     }
 }

KeeCloud/WebRequests/EntryCredentials.cs

+using KeePassLib;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+
+namespace KeeCloud.WebRequests
+{
+    /// <summary>
+    /// Network credentials created from a KeePass entry
+    /// </summary>
+    public class EntryCredentials : ICredentials
+    {
+        private readonly NetworkCredential credential;
+
+        public EntryCredentials(PwEntry entry)
+        {
+            this.credential = new NetworkCredential(GetEntry(entry, StandardProtectedStrings.Username),
+                GetEntry(entry, StandardProtectedStrings.Password));
+        }
+
+        private static string GetEntry(PwEntry entry, string key)
+        {
+            return entry.Strings.Get(key).ReadString();
+        }
+
+        NetworkCredential ICredentials.GetCredential(Uri uri, string authType)
+        {
+            return this.credential;
+        }
+    }
+}

KeeCloud/WebRequests/ProviderWebRequest.cs

 using KeeCloud.Providers;
+using KeeCloud.Utilities;
+using KeePass.Plugins;
 using KeePassLib.Serialization;
 using System;
 using System.IO;
+using System.Linq;
 using System.Net;
 
 namespace KeeCloud.WebRequests
     {
         private readonly Uri requestUri;
         private readonly IProvider provider;
+        private IPluginHost host;
 
         RequestStream requestStream = new RequestStream();
 
-        public ProviderWebRequest(Uri uri, IProvider provider)
+        public ProviderWebRequest(Uri uri, IProvider provider, IPluginHost host)
         {
             this.Headers = new WebHeaderCollection();
 
             this.requestUri = uri;
             this.provider = provider;
+            this.host = host;
         }
 
         public override Uri RequestUri
         {
             if (this.Method == IOConnection.WrmDeleteFile)
             {
-                this.provider.Delete(this.Credentials);
+                this.provider.Delete(this.GetCredentials());
                 return new SuccessWebResponse();
             }
             else if (this.Method == IOConnection.WrmMoveFile)
             {
                 var destination = Headers[IOConnection.WrhMoveFileTo];
-                this.provider.Move(new Uri(destination), this.Credentials);
+                this.provider.Move(new Uri(destination), this.GetCredentials());
                 return new SuccessWebResponse();
             }
             else if ((this.Method ?? string.Empty).ToLowerInvariant() == "post")
             {
-                this.provider.Put(this.requestStream.GetReadableStream(), this.Credentials);
+                this.provider.Put(this.requestStream.GetReadableStream(), this.GetCredentials());
                 return new SuccessWebResponse();
             }
             else
             {
-                Stream stream = this.provider.Get(this.Credentials);
+                Stream stream = this.provider.Get(this.GetCredentials());
                 return new GetWebResponse(stream);
             }
         }
+
+        /// <summary>
+        /// There are 2 ways that credentials can be provided. They can be entered directly into the form
+        /// or they can put the title of an entry in the form. If a DB is open, and the username matches the title,
+        /// and no password is provided, and the URL has a protocol prefix that matches the service, we'll use that instead
+        /// </summary>
+        /// <returns></returns>
+        private ICredentials GetCredentials()
+        {
+            var basicCredential = this.Credentials.GetCredential(this.requestUri, "basic");
+            if (basicCredential != null &&
+                !string.IsNullOrEmpty(basicCredential.UserName) &&
+                string.IsNullOrEmpty(basicCredential.Password) &&
+                this.host != null &&
+                this.host.Database.IsOpen)
+            {
+                var pwQuery = from pe in this.host.Database.GetAllPasswords()
+                              where pe.EntryStringEquals(StandardProtectedStrings.Title, basicCredential.UserName) &&
+                                    pe.EntryStringNotNullOrEmpty(StandardProtectedStrings.Username) &&
+                                    pe.EntryStringNotNullOrEmpty(StandardProtectedStrings.Password) &&
+                                    pe.EntryStringExistsAndContidtionMet(StandardProtectedStrings.Url,
+                                        value => ProtocolEqualsExpectedProtocol(value))
+                              select pe;
+
+                var entry = pwQuery.FirstOrDefault();
+                if (entry == null)
+                    return this.Credentials;
+                else
+                    return new EntryCredentials(entry);
+            }
+            else
+                return this.Credentials;
+        }
+
+        private bool ProtocolEqualsExpectedProtocol(string url)
+        {
+            try
+            {
+                var entryUri = new Uri(url);
+
+                return !string.IsNullOrEmpty(this.requestUri.Scheme) &&
+                    !string.IsNullOrEmpty(entryUri.Scheme) &&
+                    entryUri.Scheme.ToLowerInvariant() == this.requestUri.Scheme.ToLowerInvariant();
+            }
+            catch
+            {
+                return false;
+            }
+        }
     }
 }

KeeCloud/WebRequests/ProviderWebRequestCreator.cs

-using System;
+using KeePass.Plugins;
+using System;
 using System.Net;
 
 namespace KeeCloud.WebRequests
 {
     public class ProviderWebRequestCreator : IWebRequestCreate
     {
-        public static readonly ProviderWebRequestCreator Instance = new ProviderWebRequestCreator();
-        private ProviderWebRequestCreator()
+        private readonly IPluginHost host;
+
+        public ProviderWebRequestCreator(IPluginHost host)
         {
+            this.host = host;
         }
 
         public WebRequest Create(Uri uri)
         {
             var supported = ProviderRegistry.GetProviderForUri(uri);
-            return new ProviderWebRequest(uri, supported.Create(uri));
+            return new ProviderWebRequest(uri, supported.Create(uri), this.host);
         }
     }
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.