示例#1
0
		private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
		{
			Debug.Assert(strFile != null);
			if(strFile == null) throw new ArgumentNullException("strFile");
			Debug.Assert(pbKeyData != null);
			if(pbKeyData == null) throw new ArgumentNullException("pbKeyData");

			IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
			using(Stream s = IOConnection.OpenWrite(ioc))
			{
				using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(s))
				{
					xw.WriteStartDocument();
					xw.WriteStartElement(RootElementName); // <KeyFile>

					xw.WriteStartElement(MetaElementName); // <Meta>
					xw.WriteStartElement(VersionElementName); // <Version>
					xw.WriteString("1.00");
					xw.WriteEndElement(); // </Version>
					xw.WriteEndElement(); // </Meta>

					xw.WriteStartElement(KeyElementName); // <Key>

					xw.WriteStartElement(KeyDataElementName); // <Data>
					xw.WriteString(Convert.ToBase64String(pbKeyData));
					xw.WriteEndElement(); // </Data>

					xw.WriteEndElement(); // </Key>

					xw.WriteEndElement(); // </KeyFile>
					xw.WriteEndDocument();
				}
			}
		}
示例#2
0
        private static void OnStartCheck()
        {
            // NativeProgressDialog dlg = null;
            // if(m_tsResultsViewer == null)
            // {
            //	dlg = new NativeProgressDialog();
            //	dlg.StartLogging(KPRes.Wait + "...", false);
            // }

            try
            {
                IOWebClient webClient = new IOWebClient();
                IOConnection.ConfigureWebClient(webClient);

                Uri uri = new Uri(m_strVersionURL);

                webClient.DownloadDataCompleted +=
                    new DownloadDataCompletedEventHandler(OnDownloadCompleted);

                webClient.DownloadDataAsync(uri);
            }
            // catch(NotImplementedException)
            // {
            //	ReportStatusEx(KLRes.FrameworkNotImplExcp, true);
            // }
            catch (Exception) { }

            // if(dlg != null) dlg.EndLogging();
        }
示例#3
0
        private bool TestConnectionEx()
        {
            bool bResult = true;
            bool bOK = m_btnOK.Enabled, bCancel = m_btnCancel.Enabled;
            bool bCombo = m_cmbCredSaveMode.Enabled;

            m_btnOK.Enabled           = m_btnCancel.Enabled = m_tbUrl.Enabled =
                m_tbUserName.Enabled  = m_tbPassword.Enabled =
                    m_btnHelp.Enabled = m_cmbCredSaveMode.Enabled = false;

            Application.DoEvents();

            try { IOConnection.OpenRead(m_ioc).Close(); }
            catch (Exception exTest)
            {
                MessageService.ShowWarning(m_ioc.GetDisplayName(), exTest.Message);
                bResult = false;
            }

            m_btnOK.Enabled           = bOK;
            m_btnCancel.Enabled       = bCancel;
            m_cmbCredSaveMode.Enabled = bCombo;
            m_btnHelp.Enabled         = m_tbUserName.Enabled = m_tbUrl.Enabled =
                m_tbPassword.Enabled  = true;
            return(bResult);
        }
示例#4
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider
                                  fileFormat, IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }
            if (fileFormat == null)
            {
                throw new ArgumentNullException("fileFormat");
            }
            if (fileFormat.RequiresFile && (iocOutput == null))
            {
                throw new ArgumentNullException("iocOutput");
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }
            if (!fileFormat.SupportsExport)
            {
                return(false);
            }
            if (!fileFormat.TryBeginExport())
            {
                return(false);
            }

            bool bExistedAlready = true;             // No deletion by default
            bool bResult         = false;

            try
            {
                bExistedAlready = (fileFormat.RequiresFile ? IOConnection.FileExists(
                                       iocOutput) : false);
                Stream s = (fileFormat.RequiresFile ? IOConnection.OpenWrite(
                                iocOutput) : null);

                try { bResult = fileFormat.Export(pwExportInfo, s, slLogger); }
                finally { if (s != null)
                          {
                              s.Close();
                          }
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            if (fileFormat.RequiresFile && !bResult && !bExistedAlready)
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch (Exception) { }
            }

            return(bResult);
        }
示例#5
0
        private bool TestConnectionEx()
        {
            bool bResult = true;
            bool bOK = m_btnOK.Enabled, bCancel = m_btnCancel.Enabled;
            bool bCombo = m_cmbCredSaveMode.Enabled;

            m_btnOK.Enabled           = m_btnCancel.Enabled = m_tbUrl.Enabled =
                m_tbUserName.Enabled  = m_tbPassword.Enabled =
                    m_btnHelp.Enabled = m_cmbCredSaveMode.Enabled = false;

            Application.DoEvents();

            try
            {
                if (!IOConnection.FileExists(m_ioc, true))
                {
                    throw new FileNotFoundException();
                }
            }
            catch (Exception exTest)
            {
                MessageService.ShowWarning(m_ioc.GetDisplayName(), exTest.Message);
                bResult = false;
            }

            m_btnOK.Enabled           = bOK;
            m_btnCancel.Enabled       = bCancel;
            m_cmbCredSaveMode.Enabled = bCombo;
            m_btnHelp.Enabled         = m_tbUserName.Enabled = m_tbUrl.Enabled =
                m_tbPassword.Enabled  = true;
            return(bResult);
        }
示例#6
0
        public static bool Save(IOConnectionInfo ioc, Info Info)
        {
            Stream sOut = null;

            try
            {
                sOut = IOConnection.OpenWrite(ioc);

                XmlWriterSettings xws = new XmlWriterSettings();
                xws.CloseOutput = true;
                xws.Encoding    = StrUtil.Utf8;
                xws.Indent      = true;
                xws.IndentChars = "\t";

                XmlWriter xw = XmlWriter.Create(sOut, xws);

                XmlSerializer xs = new XmlSerializer(typeof(Info));
                xs.Serialize(xw, Info);

                xw.Close();
                return(true);
            }
            catch (Exception) { Debug.Assert(false); }
            finally
            {
                if (sOut != null)
                {
                    sOut.Close();
                }
            }

            return(false);
        }
示例#7
0
		private void Construct(IOConnectionInfo iocFile, bool bThrowIfDbFile)
		{
			byte[] pbFileData = IOConnection.ReadFile(iocFile);
			if(pbFileData == null) throw new FileNotFoundException();

			if(bThrowIfDbFile && (pbFileData.Length >= 8))
			{
				uint uSig1 = MemUtil.BytesToUInt32(MemUtil.Mid(pbFileData, 0, 4));
				uint uSig2 = MemUtil.BytesToUInt32(MemUtil.Mid(pbFileData, 4, 4));

				if(((uSig1 == KdbxFile.FileSignature1) &&
					(uSig2 == KdbxFile.FileSignature2)) ||
					((uSig1 == KdbxFile.FileSignaturePreRelease1) &&
					(uSig2 == KdbxFile.FileSignaturePreRelease2)) ||
					((uSig1 == KdbxFile.FileSignatureOld1) &&
					(uSig2 == KdbxFile.FileSignatureOld2)))
#if KeePassLibSD
					throw new Exception(KLRes.KeyFileDbSel);
#else
					throw new InvalidDataException(KLRes.KeyFileDbSel);
#endif
			}

			byte[] pbKey = LoadXmlKeyFile(pbFileData);
			if(pbKey == null) pbKey = LoadKeyFile(pbFileData);

			if(pbKey == null) throw new InvalidOperationException();

			m_strPath = iocFile.Path;
			m_pbKeyData = new ProtectedBinary(true, pbKey);

			MemUtil.ZeroByteArray(pbKey);
		}
示例#8
0
        private static List <UpdateComponentInfo> LoadInfoFile(string strUrl)
        {
            try
            {
                IOConnectionInfo ioc = IOConnectionInfo.FromPath(strUrl.Trim());

                byte[] pb;
                using (Stream s = IOConnection.OpenRead(ioc))
                {
                    pb = MemUtil.Read(s);
                }

                if (ioc.Path.EndsWith(".gz", StrUtil.CaseIgnoreCmp))
                {
                    // Decompress in try-catch, because some web filters
                    // incorrectly pre-decompress the returned data
                    // https://sourceforge.net/projects/keepass/forums/forum/329221/topic/4915083
                    try
                    {
                        byte[] pbDec = MemUtil.Decompress(pb);
                        List <UpdateComponentInfo> l = LoadInfoFilePriv(pbDec, ioc);
                        if (l != null)
                        {
                            return(l);
                        }
                    }
                    catch (Exception) { }
                }

                return(LoadInfoFilePriv(pb, ioc));
            }
            catch (Exception) { }

            return(null);
        }
示例#9
0
		private static List<UpdateComponentInfo> LoadInfoFile(string strUrl)
		{
			try
			{
				IOConnectionInfo ioc = IOConnectionInfo.FromPath(strUrl.Trim());

				Stream s = IOConnection.OpenRead(ioc);
				if(s == null) throw new InvalidOperationException();
				MemoryStream ms = new MemoryStream();
				MemUtil.CopyStream(s, ms);
				s.Close();
				byte[] pb = ms.ToArray();
				ms.Close();

				if(ioc.Path.EndsWith(".gz", StrUtil.CaseIgnoreCmp))
				{
					// Decompress in try-catch, because some web filters
					// incorrectly pre-decompress the returned data
					// https://sourceforge.net/projects/keepass/forums/forum/329221/topic/4915083
					try
					{
						byte[] pbDec = MemUtil.Decompress(pb);
						List<UpdateComponentInfo> l = LoadInfoFilePriv(pbDec, ioc);
						if(l != null) return l;
					}
					catch(Exception) { }
				}

				return LoadInfoFilePriv(pb, ioc);
			}
			catch(Exception) { }

			return null;
		}
示例#10
0
        public void TestSyncWhenRemoteDeleted()
        {
            //create the default database:
            TestKp2aApp app = SetupAppWithDefaultDatabase();

            IOConnection.DeleteFile(new IOConnectionInfo {
                Path = DefaultFilename
            });
            //save it and reload it so we have a base version ("remote" and in the cache)
            SaveDatabase(app);
            app = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);
            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.LoadedFromRemoteInSyncId);

            //delete remote:
            IOConnection.DeleteFile(new IOConnectionInfo {
                Path = DefaultFilename
            });

            string resultMessage;
            bool   wasSuccessful;

            //sync:
            Synchronize(app, out wasSuccessful, out resultMessage);
            Assert.IsTrue(wasSuccessful);
            Assert.AreEqual(resultMessage, app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));

            //ensure the file is back here:
            var app2 = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            AssertDatabasesAreEqual(app.GetDb().KpDatabase, app2.GetDb().KpDatabase);
        }
示例#11
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider
                                  fileFormat, IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }
            if (fileFormat == null)
            {
                throw new ArgumentNullException("fileFormat");
            }
            if (fileFormat.RequiresFile && (iocOutput == null))
            {
                throw new ArgumentNullException("iocOutput");
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }
            if (!fileFormat.SupportsExport)
            {
                return(false);
            }
            if (!fileFormat.TryBeginExport())
            {
                return(false);
            }

            // bool bExistedAlready = File.Exists(strOutputFile);
            bool bExistedAlready = (fileFormat.RequiresFile ? IOConnection.FileExists(
                                        iocOutput) : false);

            // FileStream fsOut = new FileStream(strOutputFile, FileMode.Create,
            //	FileAccess.Write, FileShare.None);
            Stream sOut = (fileFormat.RequiresFile ? IOConnection.OpenWrite(
                               iocOutput) : null);

            bool bResult = false;

            try { bResult = fileFormat.Export(pwExportInfo, sOut, slLogger); }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            if (sOut != null)
            {
                sOut.Close();
            }

            if (fileFormat.RequiresFile && (bResult == false) && (bExistedAlready == false))
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch (Exception) { }
            }

            return(bResult);
        }
示例#12
0
        public static byte[] HashFile(IOConnectionInfo iocFile)
        {
            if (iocFile == null)
            {
                Debug.Assert(false); return(null);
            }                                                                     // Assert only

            Stream sIn;

            try
            {
                sIn = IOConnection.OpenRead(iocFile);
                if (sIn == null)
                {
                    throw new FileNotFoundException();
                }
            }
            catch (Exception) { return(null); }

            byte[] pbHash;
            try
            {
                SHA256Managed sha256 = new SHA256Managed();
                pbHash = sha256.ComputeHash(sIn);
            }
            catch (Exception) { Debug.Assert(false); sIn.Close(); return(null); }

            sIn.Close();
            return(pbHash);
        }
        public void TestLoadEditSaveWhenDeleted()
        {
            //create the default database:
            IKp2aApp app = SetupAppWithDefaultDatabase();

            IOConnection.DeleteFile(new IOConnectionInfo {
                Path = DefaultFilename
            });
            //save it and reload it so we have a base version
            SaveDatabase(app);
            app = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            //delete the file:
            File.Delete(DefaultFilename);

            //modify the database by adding a group:
            app.GetDb().KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "TestGroup", PwIcon.Apple), true);
            //save the database again:
            _testCacheSupervisor.Reset();
            SaveDatabase(app);
            Assert.IsNull(((TestKp2aApp)app).LastYesNoCancelQuestionTitle);
            _testCacheSupervisor.AssertNoCall();

            //load database to a new app instance:
            IKp2aApp resultApp = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            //ensure the change was saved:
            AssertDatabasesAreEqual(app.GetDb().KpDatabase, resultApp.GetDb().KpDatabase);
        }
示例#14
0
        private string RecreateKeyFile()
        {
            ulong uVersion = m_vRecFormat[m_cmbRecFormat.SelectedIndex].Version;

            string strHash = StrUtil.RemoveWhiteSpace(m_tbRecKeyHash.Text);

            // If the hash is empty, set it to null in order to generate one
            if (strHash.Length == 0)
            {
                strHash = null;
            }

            KfxFile kf = KfxFile.Create(uVersion, m_tbRecKey.Text, strHash);

            // Ask for the file path after verifying the key hash
            string strFilePath = GetKeyFilePath();

            if (string.IsNullOrEmpty(strFilePath))
            {
                return(null);
            }

            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath);

            using (Stream s = IOConnection.OpenWrite(ioc))
            {
                kf.Save(s);
            }

            return(strFilePath);
        }
示例#15
0
        public void TestSimpleSyncCases()
        {
            //create the default database:
            TestKp2aApp app = SetupAppWithDefaultDatabase();


            IOConnection.DeleteFile(new IOConnectionInfo {
                Path = DefaultFilename
            });
            //save it and reload it so we have a base version ("remote" and in the cache)
            SaveDatabase(app);
            app = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);
            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.LoadedFromRemoteInSyncId);

            string resultMessage;
            bool   wasSuccessful;

            //sync without changes on any side:
            Synchronize(app, out wasSuccessful, out resultMessage);
            Assert.IsTrue(wasSuccessful);
            Assert.AreEqual(resultMessage, app.GetResourceString(UiStringKey.FilesInSync));

            //go offline:
            TestFileStorage.Offline = true;

            //sync when offline (->error)
            Synchronize(app, out wasSuccessful, out resultMessage);
            Assert.IsFalse(wasSuccessful);
            Assert.AreEqual(resultMessage, "offline");

            //modify the database by adding a group:
            app.GetDb().KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "TestGroup", PwIcon.Apple), true);
            //save the database again (will be saved locally only)
            SaveDatabase(app);

            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.CouldntSaveToRemoteId);

            //go online again:
            TestFileStorage.Offline = false;

            //sync with local changes only (-> upload):
            Synchronize(app, out wasSuccessful, out resultMessage);
            Assert.IsTrue(wasSuccessful);
            Assert.AreEqual(resultMessage, app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));

            //ensure both files are identical and up to date now:
            TestFileStorage.Offline = true;
            var appOfflineLoaded = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.CouldntOpenFromRemoteId);
            TestFileStorage.Offline = false;
            var appRemoteLoaded = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.LoadedFromRemoteInSyncId);

            AssertDatabasesAreEqual(app.GetDb().KpDatabase, appOfflineLoaded.GetDb().KpDatabase);
            AssertDatabasesAreEqual(app.GetDb().KpDatabase, appRemoteLoaded.GetDb().KpDatabase);
        }
示例#16
0
        private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
        {
            Debug.Assert(strFile != null);
            if (strFile == null)
            {
                throw new ArgumentNullException("strFile");
            }
            Debug.Assert(pbKeyData != null);
            if (pbKeyData == null)
            {
                throw new ArgumentNullException("pbKeyData");
            }

            IOConnectionInfo ioc  = IOConnectionInfo.FromPath(strFile);
            Stream           sOut = IOConnection.OpenWrite(ioc);

#if KeePassUAP
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = StrUtil.Utf8;
            xws.Indent   = false;

            XmlWriter xtw = XmlWriter.Create(sOut, xws);
#else
            XmlTextWriter xtw = new XmlTextWriter(sOut, StrUtil.Utf8);
#endif

            xtw.WriteStartDocument();
            xtw.WriteWhitespace("\r\n");
            xtw.WriteStartElement(RootElementName);             // KeyFile
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteStartElement(MetaElementName);    // Meta
            xtw.WriteWhitespace("\r\n\t\t");
            xtw.WriteStartElement(VersionElementName); // Version
            xtw.WriteString("1.00");
            xtw.WriteEndElement();                     // End Version
            xtw.WriteWhitespace("\r\n\t");
            xtw.WriteEndElement();                     // End Meta
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteStartElement(KeyElementName);             // Key
            xtw.WriteWhitespace("\r\n\t\t");

            xtw.WriteStartElement(KeyDataElementName); // Data
            xtw.WriteString(Convert.ToBase64String(pbKeyData));
            xtw.WriteEndElement();                     // End Data
            xtw.WriteWhitespace("\r\n\t");

            xtw.WriteEndElement();             // End Key
            xtw.WriteWhitespace("\r\n");

            xtw.WriteEndElement();             // RootElementName
            xtw.WriteWhitespace("\r\n");
            xtw.WriteEndDocument();            // End KeyFile
            xtw.Close();

            sOut.Close();
        }
示例#17
0
        private static void GenerateKfb(StringBuilder sb, PwDatabase pd,
                                        string strDbFile, string strKeyFile,
                                        GFunc <string, string> h, GFunc <string, string> ne, GFunc <string, string> ltrPath,
                                        string strFillInit, string strFillInitEx, string strFillEnd, string strFill)
        {
            string strContent;

            using (Stream s = IOConnection.OpenRead(IOConnectionInfo.FromPath(
                                                        strKeyFile)))
            {
                using (StreamReader sr = new StreamReader(s, StrUtil.Utf8, true))
                {
                    strContent = sr.ReadToEnd();
                }
            }

            // Internet Explorer 11 does not support the 'tab-size' CSS property
            strContent = strContent.Replace("\t", "    ");

            string strNlCode = (new PwUuid(true)).ToHexString();

            strContent = StrUtil.NormalizeNewLines(strContent, false);
            strContent = strContent.Replace("\n", strNlCode);             // Prevent <br />

            strContent = StrUtil.StringToHtml(strContent, false);

            strContent = strContent.Replace(strNlCode, MessageService.NewLine);

            sb.AppendLine("<p><strong>" + h(KPRes.KeyFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strKeyFile))) + strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strDbFile))) + strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<p><strong>" + h(KPRes.KeyFileContent) + ":</strong></p>");
            sb.AppendLine(strFillInit);
            sb.Append("<pre>");
            sb.Append(strContent);
            sb.AppendLine("</pre>");
            sb.AppendLine(strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");
            sb.AppendLine("<li>" + h(KPRes.KeyFileFromBackup) + ":");
            sb.AppendLine("<ul class=\"withspc\">");
            sb.AppendLine("<li><p>" + Beautify(h(KPRes.KeyFileFromBackupF2)) + "</p></li>");
            sb.AppendLine("<li><p>" + h(KPRes.KeyFileFromBackupT) + "</p></li>");
            sb.AppendLine("</ul></li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");
        }
示例#18
0
        public void TestSyncWhenConflict()
        {
            //create the default database:
            TestKp2aApp app = SetupAppWithDefaultDatabase();

            IOConnection.DeleteFile(new IOConnectionInfo {
                Path = DefaultFilename
            });
            //save it and reload it so we have a base version ("remote" and in the cache)
            SaveDatabase(app);
            app = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);
            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.LoadedFromRemoteInSyncId);

            var app2 = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            app2.FileStorage = app.TestFileStorage;             //give app2 direct access to the remote file
            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.LoadedFromRemoteInSyncId);

            //go offline:
            TestFileStorage.Offline = true;


            string resultMessage;
            bool   wasSuccessful;

            //modify the database by adding a group in both apps:
            PwGroup newGroup1 = new PwGroup(true, true, "TestGroup", PwIcon.Apple);

            app.GetDb().KpDatabase.RootGroup.AddGroup(newGroup1, true);
            PwGroup newGroup2 = new PwGroup(true, true, "TestGroupApp2", PwIcon.Apple);

            app2.GetDb().KpDatabase.RootGroup.AddGroup(newGroup2, true);
            //save the database again (will be saved locally only for "app")
            SaveDatabase(app);
            _testCacheSupervisor.AssertSingleCall(TestCacheSupervisor.CouldntSaveToRemoteId);

            //go online again:
            TestFileStorage.Offline = false;

            //...and remote only for "app2":
            SaveDatabase(app2);

            //try to sync:
            Synchronize(app, out wasSuccessful, out resultMessage);

            Assert.IsTrue(wasSuccessful);
            Assert.AreEqual(UiStringKey.SynchronizedDatabaseSuccessfully.ToString(), resultMessage);

            //build app2 with the newGroup1:
            app2.GetDb().KpDatabase.RootGroup.AddGroup(newGroup1, true);

            var app3 = LoadDatabase(DefaultFilename, DefaultPassword, DefaultKeyfile);

            AssertDatabasesAreEqual(app.GetDb().KpDatabase, app2.GetDb().KpDatabase);
            AssertDatabasesAreEqual(app.GetDb().KpDatabase, app3.GetDb().KpDatabase);
        }
        /// <summary>
        /// Get a key for an existing database.  First, the key file is located, either because its location
        /// and filename are the same as the database path (with the exception of the extension), or the user
        /// is asked.  Then, the key file is decrypted using a private key.
        /// </summary>
        /// <param name="strPath">Full filename of the database file.</param>
        /// <returns>A byte array with the key, or null if an error occurs.  If an error occurs, user is
        /// notified of the error.</returns>
        byte[] GetExistingKey(IOConnectionInfo ioc)
        {
            Stream stream = null;

            try
            {
                string           newpath = UrlUtil.StripExtension(ioc.Path) + "." + CertProtKeyFileExtension;
                IOConnectionInfo keyIoc  = ioc.CloneDeep();
                keyIoc.Path = newpath;
                stream      = IOConnection.OpenRead(keyIoc);
            }
            catch (Exception e)
            {
                // strPath may be a URL (even if IsLocalFile returns true?),
                // whatever the reason, fall through and the user can pick a
                // local file as the key file
            }

            if (stream == null || !stream.CanRead)
            {
                // fall back on opening a local file
                // FUTURE ENHANCEMENT: allow user to enter a URL and name/pwd as well

                OpenFileDialog ofd = UIUtil.CreateOpenFileDialog("KeePassX509Provider", UIUtil.CreateFileTypeFilter(CertProtKeyFileExtension, "x05KeyFile", true), 1, CertProtKeyFileExtension, false /* multi-select */, true);

                if (ofd.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }
                stream = IOConnection.OpenRead(IOConnectionInfo.FromPath(ofd.FileName));
            }
            try
            {
                BinaryReader reader = new BinaryReader(stream);
                byte[]       p7m    = reader.ReadBytes(MAX_KEY_FILE_LENGTH);
                // URL streams don't support seeking, and so Position doesn't work
                //bool tooBig = stream.Position >= MAX_KEY_FILE_LENGTH;
                bool tooBig = p7m.Length >= MAX_KEY_FILE_LENGTH;
                reader.Close();

                if (tooBig)
                {
                    MessageBox.Show("Kes File ist to big");
                    return(null);
                }
                Certmanager cert_mgr = new Certmanager();
                return(cert_mgr.DecryptMsg(p7m));
            }
            catch (SystemException ex)  // covers IOException and CryptographicException
            {
                MessageBox.Show("Error at encryption or IO error!\nIf you used a smart card for encryption, please provide/plugin fist!");
                return(null);
            }
        }
示例#20
0
 public Stream OpenFileForRead(IOConnectionInfo ioc)
 {
     try
     {
         return(IOConnection.OpenRead(ioc));
     }
     catch (WebException ex)
     {
         ConvertException(ioc, ex);
         throw;
     }
 }
示例#21
0
 private void DisconnectIO()
 {
     if (ioConnection != null)
     {
         ioConnection.Disconnect();
         ioConnection = null;
     }
     if (ConnectionEventCallback != null)
     {
         ConnectionEventCallback.Invoke(Enum_ConnectionEvent.DISCONNECTED_IO, null);
     }
 }
示例#22
0
        private void GetOnlineStatus()
        {
            var pwdSha       = GetPasswordSHA();
            var truncatedSha = pwdSha.Substring(0, 5);

            var url = "https://api.pwnedpasswords.com/range/" + truncatedSha;

            IOConnectionInfo ioc = new IOConnectionInfo
            {
                Path = url
            };

            try
            {
                using (Stream stream = IOConnection.OpenRead(ioc))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string responseFromServer = reader.ReadToEnd();
                        var    lines = responseFromServer.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                        Status = PluginOptions.SecureText;

                        foreach (var line in lines)
                        {
                            string fullSha = truncatedSha + line;
                            var    compare = string.Compare(pwdSha, fullSha.Substring(0, pwdSha.Length), StringComparison.Ordinal);

                            if (compare == 0)
                            {
                                var tokens = line.Split(':');
                                Status          = PluginOptions.InsecureText;
                                insecureWarning = true;

                                if (PluginOptions.BreachCountDetails)
                                {
                                    Status += " (password count: " + tokens[1].Trim() + ")";
                                }

                                break;
                            }
                        }

                        reader.Close();
                        stream.Close();
                    }
            }
            catch
            {
                Status = "HIBP API error";
            }
        }
示例#23
0
        private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
        {
            Debug.Assert(strFile != null);
            if (strFile == null)
            {
                throw new ArgumentNullException("strFile");
            }
#endif
            Debug.Assert(pbKeyData != null);
            if (pbKeyData == null)
            {
                throw new ArgumentNullException("pbKeyData");
            }

#if ModernKeePassLib
            var fileContents = new byte[0];
            var ioc          = IOConnectionInfo.FromByteArray(fileContents);
#else
            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
#endif
            using (Stream s = IOConnection.OpenWrite(ioc))
            {
                using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(s))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement(RootElementName);    // <KeyFile>

                    xw.WriteStartElement(MetaElementName);    // <Meta>
                    xw.WriteStartElement(VersionElementName); // <Version>
                    xw.WriteString("1.00");
                    xw.WriteEndElement();                     // </Version>
                    xw.WriteEndElement();                     // </Meta>

                    xw.WriteStartElement(KeyElementName);     // <Key>

                    xw.WriteStartElement(KeyDataElementName); // <Data>
                    xw.WriteString(Convert.ToBase64String(pbKeyData));
                    xw.WriteEndElement();                     // </Data>

                    xw.WriteEndElement();                     // </Key>

                    xw.WriteEndElement();                     // </KeyFile>
                    xw.WriteEndDocument();
                }
#if ModernKeePassLib
                return(((MemoryStream)s).ToArray());
#endif
            }
        }
示例#24
0
        public void ConnectIO()
        {
            if (ioConnection == null)
            {
                ioConnection = new IOConnection();
                ioConnection.IOTransition += ioConnection_IOTransition;
            }
            ioConnection.Connect(vsDevice);

            // STATECHANGED_IO
            if (ConnectionEventCallback != null)
            {
                ConnectionEventCallback.Invoke(Enum_ConnectionEvent.CONNECTED_IO, ioConnection);
            }
        }
示例#25
0
        public static bool?Import(PwDatabase pd, FileFormatProvider fmtImp,
                                  IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey)
        {
            if (pd == null)
            {
                Debug.Assert(false); return(false);
            }
            if (fmtImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (iocImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (cmpKey == null)
            {
                cmpKey = new CompositeKey();
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            PwDatabase pdImp = new PwDatabase();

            pdImp.New(new IOConnectionInfo(), cmpKey);
            pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep();

            Stream s = IOConnection.OpenRead(iocImp);

            if (s == null)
            {
                throw new FileNotFoundException(iocImp.GetDisplayName() +
                                                MessageService.NewLine + KPRes.FileNotFoundError);
            }

            try { fmtImp.Import(pdImp, s, null); }
            finally { s.Close(); }

            pd.MergeIn(pdImp, mm);
            return(true);
        }
示例#26
0
        private bool TestConnectionEx()
        {
            bool bResult = true;
            bool bOK = m_btnOK.Enabled, bCancel = m_btnCancel.Enabled;
            bool bCombo = m_cmbCredSaveMode.Enabled;

            m_btnOK.Enabled           = m_btnCancel.Enabled = m_tbUrl.Enabled =
                m_tbUserName.Enabled  = m_tbPassword.Enabled =
                    m_btnHelp.Enabled = m_cmbCredSaveMode.Enabled = false;

            Application.DoEvents();

            try
            {
                if (!IOConnection.FileExists(m_ioc, true))
                {
                    throw new FileNotFoundException();
                }
            }
            catch (Exception exTest)
            {
                if (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)
                {
                    MessageService.ShowWarningExcp(m_ioc.GetDisplayName(), exTest);
                }
                else
                {
                    string strError = exTest.Message;
                    if ((exTest.InnerException != null) &&
                        !string.IsNullOrEmpty(exTest.InnerException.Message))
                    {
                        strError += MessageService.NewParagraph +
                                    exTest.InnerException.Message;
                    }

                    MessageService.ShowWarning(m_ioc.GetDisplayName(), strError);
                }

                bResult = false;
            }

            m_btnOK.Enabled           = bOK;
            m_btnCancel.Enabled       = bCancel;
            m_cmbCredSaveMode.Enabled = bCombo;
            m_btnHelp.Enabled         = m_tbUserName.Enabled = m_tbUrl.Enabled =
                m_tbPassword.Enabled  = true;
            return(bResult);
        }
示例#27
0
        private void Microscan_App_Loaded(object sender, RoutedEventArgs e)
        {
            WFHost1.Child = BufferView1;

            m_Coord   = new VsCoordinator();   // Starts Backplane
            m_Job     = new JobStep();
            m_RepCon1 = new ReportConnection();
            m_IO      = new IOConnection();

            // Set DEVICENAME to your units name
            DEVICENAME = "SoftSys1";
            //DEVICENAME = "MicroHAWK1A48C4";
            m_RepCon1.NewReport   += new EventHandler <ReportConnectionEventArgs>(m_RepCon1_NewReport);
            m_Coord.OnDeviceFocus += new _IVsCoordinatorEvents_OnDeviceFocusEventHandler(m_Coord_OnDeviceFocus);
            m_Coord.DeviceFocusSetOnDiscovery(DEVICENAME, -1);
        }
示例#28
0
        public void Apply(AceApplyFlags f)
        {
            AceSecurity    aceSec = this.Security;          // m_sec might be null
            AceIntegration aceInt = this.Integration;       // m_int might be null

            if ((f & AceApplyFlags.Proxy) != AceApplyFlags.None)
            {
                IOConnection.SetProxy(aceInt.ProxyType, aceInt.ProxyAddress,
                                      aceInt.ProxyPort, aceInt.ProxyUserName, aceInt.ProxyPassword);
            }

            if ((f & AceApplyFlags.Ssl) != AceApplyFlags.None)
            {
                IOConnection.SslCertsAcceptInvalid = aceSec.SslCertsAcceptInvalid;
            }
        }
示例#29
0
        /// <summary>
        /// Common program initialization function that can also be
        /// used by applications that use KeePass as a library
        /// (like e.g. KPScript).
        /// </summary>
        public static bool CommonInit()
        {
            int nRandomSeed = (int)DateTime.UtcNow.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            InitEnvSecurity();

            try { SelfTest.TestFipsComplianceProblems(); }
            catch (Exception exFips)
            {
                MessageService.ShowWarning(KPRes.SelfTestFailed, exFips);
                return(false);
            }

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();
            IOConnection.SetProxy(m_appConfig.Integration.ProxyType,
                                  m_appConfig.Integration.ProxyAddress, m_appConfig.Integration.ProxyPort,
                                  m_appConfig.Integration.ProxyUserName, m_appConfig.Integration.ProxyPassword);

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            LoadTranslation();
            return(true);
        }
示例#30
0
        /// <summary>
        /// Open a database. The URL may point to any supported data source.
        /// </summary>
        /// <param name="ioSource">IO connection to load the database from.</param>
        /// <param name="pwKey">Key used to open the specified database.</param>
        /// <param name="slLogger">Logger, which gets all status messages.</param>
        public void Open(IOConnectionInfo ioSource, CompositeKey pwKey,
                         IStatusLogger slLogger)
        {
            Debug.Assert(ioSource != null);
            if (ioSource == null)
            {
                throw new ArgumentNullException("ioSource");
            }
            Debug.Assert(pwKey != null);
            if (pwKey == null)
            {
                throw new ArgumentNullException("pwKey");
            }

            this.Close();

            try
            {
                m_pgRootGroup = new PwGroup(true, true, UrlUtil.StripExtension(
                                                UrlUtil.GetFileName(ioSource.Path)), PwIcon.FolderOpen);
                m_pgRootGroup.IsExpanded = true;

                m_pwUserKey = pwKey;

                m_bModified = false;

                Kdb4File kdb4 = new Kdb4File(this);
                Stream   s    = IOConnection.OpenRead(ioSource);
                kdb4.Load(s, Kdb4Format.Default, slLogger);
                s.Close();

                m_pbHashOfLastIO     = kdb4.HashOfFileOnDisk;
                m_pbHashOfFileOnDisk = kdb4.HashOfFileOnDisk;
                Debug.Assert(m_pbHashOfFileOnDisk != null);

                m_bDatabaseOpened = true;
                m_ioSource        = ioSource;
            }
            catch (Exception)
            {
                this.Clear();
                throw;
            }
        }