Example #1
0
        void StartWebsockServer(WebSocketServerConfig config)
        {
            FleckLog.Level     = LogLevel.Debug;
            FleckLog.LogAction = new Fleck2Extensions.Action <LogLevel, string, Exception>(FleckLogger);
            // Fleck library changed behaviour with recent .NET versions so we have to supply the port in the location string
            _webSocketServer = new WebSocketServer("ws://localhost:" + config.WebSocketPort, config.BindOnlyToLoopback);
            Action <IWebSocketConnection> applyConfiguration = new Action <IWebSocketConnection>(InitSocket);

            _webSocketServer.Start(applyConfiguration);
        }
Example #2
0
 /// <summary>
 /// Starts the web socket listener
 /// </summary>
 /// <param name="service">The KeePassRPCService the server should interact with.</param>
 public KeePassRPCServer(KeePassRPCService service, KeePassRPCExt keePassRPCPlugin, WebSocketServerConfig websocketConfig)
 {
     if (keePassRPCPlugin.logger != null)
     {
         keePassRPCPlugin.logger.WriteLine("Starting KPRPCServer");
     }
     Service          = service;
     KeePassRPCPlugin = keePassRPCPlugin;
     WebsocketConfig  = websocketConfig;
     StartWebsockServer(websocketConfig);
     if (keePassRPCPlugin.logger != null)
     {
         keePassRPCPlugin.logger.WriteLine("Started KPRPCServer");
     }
 }
Example #3
0
        /// <summary>
        /// The <c>Initialize</c> function is called by KeePass when
        /// you should initialize your plugin (create menu items, etc.).
        /// </summary>
        /// <param name="host">Plugin host interface. By using this
        /// interface, you can access the KeePass main window and the
        /// currently opened database.</param>
        /// <returns>true if channel registered correctly, otherwise false</returns>
        public override bool Initialize(IPluginHost host)
        {
            try
            {
                Debug.Assert(host != null);
                if (host == null)
                {
                    return(false);
                }
                _host = host;

                // Reduce Fleck library logging verbosity
                Fleck2.FleckLog.Level = Fleck2.LogLevel.Error;

                // Enable update checks
                KeePass.Util.UpdateCheckEx.SetFileSigKey(UpdateUrl, "<RSAKeyValue><Modulus>t2jki5ttRkT7D110Q5n/ZdgFZ7JGdlRDme0NvcG1Uz7CnGF40NOqWtuzW4a9p0xUN05I5JegaJ20Nu6ejuxMfOhn0jUALHYe6F2wn4yGbPHJvXLXYyc3fU7W75eWJwQabup2vKhrAjvPMSQfy05JgPcfDmLk0txuKkrPO0u3d9ZzZsYrW+GLyJAQAT9Lt87A04iQsPxB30gXv4JX7iOqtKVsWfKEzanX/zuA5XB8JEd2I7bh2u0AgUA2rnwjSkI01tb6BheruwWm5GLZhe+k/wQkgiTxLAi/HNX9BjebWvVgd7B2OpDWAq4QFLrdSlBqT8d+V1IuJeztcjKhe5lHxHDiE6/5ajmBs4/c0EmKN7bXC+fF7xbVLa+aiKQCW7rzldXx0aqP/6/+VYAXrre55nIWzuArciLT43G1DzDRTyWz+KtNm9CYd07bn1QA9a3bvQxpuM3KSo2fyfBQTcxapBNDoMnM4gKUNd3rTdDmC0j2bHN9Ikyef9ohWzgIkmLleh8Ey1TpGbWS3Y2B3AD2bmqxWgzUBUMkenmp1GglHtc448BuusPPAcibIntZMQqmaHoJ1zeNJQKGNUKCJFjbe/aeHBm/jJ7izPfR8W27D+NMhdvFOZjprmh1AVa97yQ5Zqbh1zH/gsL0XCEuNOobVaVjAsOBhXMiFnl4U4sjknE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");

                _BackgroundWorker = new BackgroundWorker();
                _BackgroundWorker.WorkerReportsProgress = true;
                _BackgroundWorker.ProgressChanged      += _BackgroundWorker_ProgressChanged;
                _BackgroundWorkerAutoResetEvent         = new AutoResetEvent(false);
                _BackgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs e)
                {
                    _BackgroundWorkerAutoResetEvent.WaitOne();
                };
                _BackgroundWorker.RunWorkerAsync();

                string debugFileName = host.CommandLineArgs["KPRPCDebug"];
                if (debugFileName != null)
                {
                    try
                    {
                        logger = new StreamWriter(debugFileName);
                        ((StreamWriter)logger).AutoFlush = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("KeePassRPC debug logger failed to initialise. No logging will be performed until KeePass is restarted with a valid debug log file location. Reason: " + ex.ToString());
                    }
                }
                if (logger != null)
                {
                    logger.WriteLine("Logger initialised.");
                }

                TLDRulesCache.Init(host.CustomConfig.GetString(
                                       "KeePassRPC.publicSuffixDomainCache.path",
                                       GetLocalConfigLocation() + "publicSuffixDomainCache.txt"));

                // The Kee client manager holds objects relating to the web socket connections managed by the Fleck2 library
                CreateClientManagers();

                if (logger != null)
                {
                    logger.WriteLine("Client managers started.");
                }
                //TODO2: set up language services

                _RPCService = new KeePassRPCService(host,
                                                    getStandardIconsBase64(host.MainWindow.ClientIcons), this);
                if (logger != null)
                {
                    logger.WriteLine("RPC service started.");
                }
                int portNew = FindKeePassRPCPort(host);

                try
                {
                    WebSocketServerConfig config = new WebSocketServerConfig();
                    config.WebSocketPort      = portNew;
                    config.BindOnlyToLoopback = host.CustomConfig.GetBool("KeePassRPC.webSocket.bindOnlyToLoopback", true);
                    config.PermittedOrigins   = DeterminePermittedOrigins();
                    _RPCServer = new KeePassRPCServer(RPCService, this, config);
                }
                catch (System.Net.Sockets.SocketException ex)
                {
                    if (ex.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse)
                    {
                        MessageBox.Show(@"KeePassRPC is already listening for connections. To allow KeePassRPC clients (e.g. Kee in your web browser) to connect to this instance of KeePass, please close all other running instances of KeePass and restart this KeePass. If you want multiple instances of KeePass to be running at the same time, you'll need to configure some of them to connect using a different communication port.

See https://forum.kee.pm/t/connection-security-levels/1075

KeePassRPC requires this port to be available: " + portNew + ". Technical detail: " + ex.ToString());
                        if (logger != null)
                        {
                            logger.WriteLine("Socket (port) already in use. KeePassRPC requires this port to be available: " + portNew + ". Technical detail: " + ex.ToString());
                        }
                    }
                    else
                    {
                        MessageBox.Show(@"KeePassRPC could not start listening for connections. To allow KeePassRPC clients (e.g. Kee in your web browser) to connect to this instance of KeePass, please fix the problem indicated in the technical detail below and restart KeePass.

KeePassRPC requires this port to be available: " + portNew + ". Technical detail: " + ex.ToString());
                        if (logger != null)
                        {
                            logger.WriteLine("Socket error. KeePassRPC requires this port to be available: " + portNew + ". Maybe check that you have no firewall or other third party security software interfering with your system. Technical detail: " + ex.ToString());
                        }
                    }
                    if (logger != null)
                    {
                        logger.WriteLine("KPRPC startup failed: " + ex.ToString());
                    }
                    _BackgroundWorkerAutoResetEvent.Set(); // terminate _BackgroundWorker
                    return(false);
                }
                if (logger != null)
                {
                    logger.WriteLine("RPC server started.");
                }

                // register to recieve events that we need to deal with

                _host.MainWindow.FileOpened  += OnKPDBOpen;
                _host.MainWindow.FileClosed  += OnKPDBClose;
                _host.MainWindow.FileCreated += OnKPDBCreated;
                _host.MainWindow.FileSaving  += OnKPDBSaving;
                _host.MainWindow.FileSaved   += OnKPDBSaved;

                _host.MainWindow.DocumentManager.ActiveDocumentSelected += OnKPDBSelected;

                // Get a reference to the 'Tools' menu item container
                ToolStripItemCollection tsMenu = _host.MainWindow.ToolsMenu.DropDownItems;

                // Add menu item for options
                _keePassRPCOptions        = new DPIScaledToolStripMenuItem("KeePassRPC (Kee) Options...");
                _keePassRPCOptions.Click += OnToolsOptions;
                tsMenu.Add(_keePassRPCOptions);

                // Add a seperator and menu item to the group context menu
                ContextMenuStrip gcm = host.MainWindow.GroupContextMenu;
                _tsSeparator1 = new ToolStripSeparator();
                gcm.Items.Add(_tsSeparator1);
                _keeRootMenu        = new DPIScaledToolStripMenuItem("Set as Kee home group");
                _keeRootMenu.Click += OnMenuSetRootGroup;
                gcm.Items.Add(_keeRootMenu);

                // not acting on upgrade info just yet but we need to track it for future proofing
                bool upgrading = refreshVersionInfo(host);

                // for debug only:
                //WelcomeForm wf = new WelcomeForm();
                //DialogResult dr = wf.ShowDialog();
                //if (dr == DialogResult.Yes)
                //    CreateNewDatabase();

                GwmWindowAddedHandler            = new EventHandler <GwmWindowEventArgs>(GlobalWindowManager_WindowAdded);
                GlobalWindowManager.WindowAdded += GwmWindowAddedHandler;
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.WriteLine("KPRPC startup failed: " + ex.ToString());
                }
                _BackgroundWorkerAutoResetEvent.Set(); // terminate _BackgroundWorker
                return(false);
            }
            if (logger != null)
            {
                logger.WriteLine("KPRPC startup succeeded.");
            }
            return(true); // Initialization successful
        }