Esempio n. 1
0
        private static XmlDocument LoadEnforcedConfigFile()
        {
#if DEBUG
            Stopwatch sw = Stopwatch.StartNew();
#endif

            g_xdEnforced = null;
            try
            {
                if (!File.Exists(g_strEnforcedConfigFile))
                {
                    return(null);
                }

                XmlDocument xd = XmlUtilEx.CreateXmlDocument();
                xd.Load(g_strEnforcedConfigFile);

                g_xdEnforced = xd;
                return(xd);
            }
            catch (Exception ex)
            {
                FileDialogsEx.ShowConfigError(g_strEnforcedConfigFile,
                                              ex.Message, false, false);
            }
#if DEBUG
            finally
            {
                sw.Stop();
            }
#endif

            return(null);
        }
Esempio n. 2
0
        public static void Save(KPTranslation kpTrl, Stream sOut,
                                IXmlSerializerEx xs)
        {
            if (xs == null)
            {
                throw new ArgumentNullException("xs");
            }

#if !KeePassLibSD
            using (GZipStream gz = new GZipStream(sOut, CompressionMode.Compress))
#else
            using (GZipOutputStream gz = new GZipOutputStream(sOut))
#endif
            {
                using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(gz))
                {
                    xs.Serialize(xw, kpTrl);
                }
            }

#if KeePassUWP
            sOut.Dispose();
#else
            sOut.Close();
#endif
        }
Esempio n. 3
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            HspFolder hspRoot = XmlUtilEx.Deserialize <HspFolder>(sInput);

            AddFolder(pwStorage.RootGroup, hspRoot, false);
        }
Esempio n. 4
0
        private static bool WriteIpcInfoFile(int nId, IpcParamEx ipcMsg)
        {
            string strPath = GetIpcFilePath(nId);

            if (string.IsNullOrEmpty(strPath))
            {
                return(false);
            }

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlUtilEx.Serialize <IpcParamEx>(ms, ipcMsg);

                    byte[] pb    = ms.ToArray();
                    byte[] pbCmp = MemUtil.Compress(pb);
                    byte[] pbEnc = CryptoUtil.ProtectData(pbCmp, IpcOptEnt,
                                                          DataProtectionScope.CurrentUser);

                    File.WriteAllBytes(strPath, pbEnc);
                }

                return(true);
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Esempio n. 5
0
        private static XmlDocument LoadEnforcedConfigFile()
        {
#if DEBUG
            Stopwatch sw = Stopwatch.StartNew();
#endif

            m_xdEnforced = null;
            try
            {
                // Performance optimization
                if (!File.Exists(m_strEnforcedConfigFile))
                {
                    return(null);
                }

                XmlDocument xmlDoc = XmlUtilEx.CreateXmlDocument();
                xmlDoc.Load(m_strEnforcedConfigFile);

                m_xdEnforced = xmlDoc;
                return(xmlDoc);
            }
            catch (Exception) { Debug.Assert(false); }
#if DEBUG
            finally
            {
                sw.Stop();
            }
#endif

            return(null);
        }
        private void SrxpSearch(SearchParameters sp, PwObjectList <PwEntry> lResults,
                                IStatusLogger sl)
        {
            PwDatabase pd = new PwDatabase();

            pd.RootGroup = SrxpFilterCloneSelf(sp);

            Dictionary <PwUuid, bool> dResults = new Dictionary <PwUuid, bool>();

            XmlDocument       xd;
            XPathNodeIterator xpIt = XmlUtilEx.FindNodes(pd, sp.SearchString, sl, out xd);

            if ((sl != null) && !sl.SetProgress(98))
            {
                return;
            }

            while (xpIt.MoveNext())
            {
                if ((sl != null) && !sl.ContinueWork())
                {
                    return;
                }

                XPathNavigator xpNav = xpIt.Current.Clone();

                while (true)
                {
                    XPathNodeType nt = xpNav.NodeType;
                    if (nt == XPathNodeType.Root)
                    {
                        break;
                    }

                    if ((nt == XPathNodeType.Element) &&
                        (xpNav.Name == KdbxFile.ElemEntry))
                    {
                        SrxpAddResult(dResults, xpNav);
                        break;
                    }

                    if (!xpNav.MoveToParent())
                    {
                        Debug.Assert(false); break;
                    }
                }
            }

            EntryHandler eh = delegate(PwEntry pe)
            {
                if (dResults.ContainsKey(pe.Uuid))
                {
                    lResults.Add(pe);
                }
                return(true);
            };

            TraverseTree(TraversalMethod.PreOrder, null, eh);
            Debug.Assert(lResults.UCount == (uint)dResults.Count);
        }
Esempio n. 7
0
        internal static void Save(TceConfig cfg)
        {
            if (cfg == null)
            {
                Debug.Assert(false); return;
            }

            try
            {
                string strDir;
                string strFile = GetFilePath(out strDir);

                if (!Directory.Exists(strDir))
                {
                    Directory.CreateDirectory(strDir);
                }

                using (FileStream fs = new FileStream(strFile, FileMode.Create,
                                                      FileAccess.Write, FileShare.None))
                {
                    XmlUtilEx.Serialize <TceConfig>(fs, cfg);
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Esempio n. 8
0
        private void DoCopyTriggers(ListViewItem[] vTriggers)
        {
            if (vTriggers == null)
            {
                return;
            }

            try
            {
                ClipboardUtil.Clear();
                if (vTriggers.Length == 0)
                {
                    return;
                }

                EcasTriggerContainer v = new EcasTriggerContainer();
                for (int iTrigger = 0; iTrigger < vTriggers.Length; ++iTrigger)
                {
                    v.Triggers.Add(vTriggers[iTrigger].Tag as EcasTrigger);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    XmlUtilEx.Serialize <EcasTriggerContainer>(ms, v);

                    ClipboardUtil.Copy(StrUtil.Utf8.GetString(ms.ToArray()), false,
                                       false, null, null, this.Handle);
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }
        }
Esempio n. 9
0
        internal static bool ImportOld(PwDatabase pwStorage, byte[] pb)
        {
            // Version 2 uses ANSI encoding, version 3 uses UTF-8
            // encoding (with BOM)
            XmlDocument dAnsi = XmlUtilEx.CreateXmlDocument();

            try
            {
                using (MemoryStream ms = new MemoryStream(pb, false))
                {
                    using (StreamReader sr = new StreamReader(ms, Encoding.Default, true))
                    {
                        dAnsi.Load(sr);

                        XmlElement xmlRoot = dAnsi.DocumentElement;

                        // Version 2 has three "ver_*" attributes,
                        // version 3 has a "version" attribute
                        if (xmlRoot.Attributes["ver_major"] == null)
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); return(false); }

            PwAgentXml2.Import(pwStorage, dAnsi);
            return(true);
        }
Esempio n. 10
0
        private void OnCtxToolsPasteTriggers(object sender, EventArgs e)
        {
            try
            {
                string strData = ClipboardUtil.GetText();

                byte[]               pbData = StrUtil.Utf8.GetBytes(strData);
                MemoryStream         ms     = new MemoryStream(pbData, false);
                EcasTriggerContainer c      = XmlUtilEx.Deserialize <EcasTriggerContainer>(ms);
                ms.Close();

                foreach (EcasTrigger t in c.Triggers)
                {
                    if (m_triggers.FindObjectByUuid(t.Uuid) != null)
                    {
                        t.Uuid = new PwUuid(true);
                    }

                    m_triggers.TriggerCollection.Add(t);
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            UpdateTriggerListEx(true);
        }
    private void saveFileButton_Click(object sender, EventArgs e)
    {
        if (secureTextBox.TextLength <= 0 || _selectedCertificate == null || string.IsNullOrWhiteSpace(keyFileLocationTextBox.Text))
        {
            MessageService.ShowWarning("All the fields are required.");
            return;
        }

        bool overwrite = false;

        if (File.Exists(keyFileLocationTextBox.Text))
        {
            overwrite = MessageService.AskYesNo($"The file '{keyFileLocationTextBox.Text}' already exists. Overwrite?", "Warning");
            if (overwrite != true)
            {
                return;
            }
        }

        var cspKey = CryptoHelpers.EncryptPassphrase(_selectedCertificate, secureTextBox.TextEx);

        using (var fs = new FileStream(keyFileLocationTextBox.Text, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.Write, FileShare.Read))
        {
            XmlUtilEx.Serialize(fs, cspKey);
        }

        DialogResult = DialogResult.OK;
    }
Esempio n. 12
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();
				}
			}
		}
Esempio n. 13
0
        private static void ImportPriv(PwGroup pgStorage, Stream s, GxiProfile p,
                                       PwDatabase pdContext, IStatusLogger sl)
        {
            StrEncodingInfo sei = StrUtil.GetEncoding(p.Encoding);
            StreamReader    srRaw;

            if ((sei != null) && (sei.Encoding != null))
            {
                srRaw = new StreamReader(s, sei.Encoding, true);
            }
            else
            {
                srRaw = new StreamReader(s, true);
            }
            string strDoc = srRaw.ReadToEnd();

            srRaw.Close();

            strDoc = Preprocess(strDoc, p);

            using (StringReader srDoc = new StringReader(strDoc))
            {
                using (XmlReader xr = XmlReader.Create(srDoc,
                                                       XmlUtilEx.CreateXmlReaderSettings()))
                {
                    XPathDocument xd = new XPathDocument(xr);

                    GxiContext c = new GxiContext(p, pdContext, pgStorage, null);

                    XPathNavigator xpDoc = xd.CreateNavigator();
                    ImportObject(xpDoc, p, p.RootXPath, "/*", GxiImporter.ImportRoot, c);
                }
            }
        }
Esempio n. 14
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            XmlDocument xmlDoc = XmlUtilEx.CreateXmlDocument();

            xmlDoc.Load(sInput);

            XmlNode xmlRoot = xmlDoc.DocumentElement;

            Debug.Assert(xmlRoot.Name == ElemRoot);

            int nNodeCount = xmlRoot.ChildNodes.Count;

            for (int i = 0; i < nNodeCount; ++i)
            {
                XmlNode xmlChild = xmlRoot.ChildNodes[i];

                if (xmlChild.Name == ElemEntry)
                {
                    ReadEntry(xmlChild, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }

                if (slLogger != null)
                {
                    slLogger.SetProgress((uint)(((i + 1) * 100) / nNodeCount));
                }
            }
        }
Esempio n. 15
0
        private static AppConfigEx LoadConfigFileEx(string strFilePath,
                                                    XmlDocument xdEnforced)
        {
            if (string.IsNullOrEmpty(strFilePath))
            {
                Debug.Assert(false); return(null);
            }

            AppConfigEx tConfig = null;

            try
            {
                if (!File.Exists(strFilePath))
                {
                    return(null);
                }

                XmlSerializerEx xs = new XmlSerializerEx(typeof(AppConfigEx));

                if (xdEnforced == null)
                {
                    using (FileStream fs = new FileStream(strFilePath,
                                                          FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        tConfig = (AppConfigEx)xs.Deserialize(fs);
                    }
                }
                else                 // Enforced configuration
                {
                    XmlDocument xd = XmlUtilEx.CreateXmlDocument();
                    xd.Load(strFilePath);

                    XmContext ctx = new XmContext(xd, AppConfigEx.GetNodeOptions,
                                                  AppConfigEx.GetNodeKey);
                    XmlUtil.MergeElements(xd.DocumentElement, xdEnforced.DocumentElement,
                                          "/" + xd.DocumentElement.Name, null, ctx);

                    using (MemoryStream msW = new MemoryStream())
                    {
                        xd.Save(msW);

                        using (MemoryStream msR = new MemoryStream(msW.ToArray(), false))
                        {
                            tConfig = (AppConfigEx)xs.Deserialize(msR);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FileDialogsEx.ShowConfigError(strFilePath, ex.Message, false, true);
            }

            if (tConfig != null)
            {
                tConfig.OnLoad();
            }
            return(tConfig);
        }
Esempio n. 16
0
        private static AppConfigEx LoadConfigFileEx(string strFilePath,
                                                    XmlDocument xdEnforced)
        {
            if (string.IsNullOrEmpty(strFilePath))
            {
                return(null);
            }

            AppConfigEx     tConfig   = null;
            XmlSerializerEx xmlSerial = new XmlSerializerEx(typeof(AppConfigEx));

            if (xdEnforced == null)
            {
                try
                {
                    using (FileStream fs = new FileStream(strFilePath,
                                                          FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        tConfig = (AppConfigEx)xmlSerial.Deserialize(fs);
                    }
                }
                catch (Exception) { } // Do not assert
            }
            else                      // Enforced configuration
            {
                try
                {
                    XmlDocument xd = XmlUtilEx.CreateXmlDocument();
                    xd.Load(strFilePath);

                    XmContext ctx = new XmContext(xd, AppConfigEx.GetNodeOptions,
                                                  AppConfigEx.GetNodeKey);
                    XmlUtil.MergeElements(xd.DocumentElement, xdEnforced.DocumentElement,
                                          "/" + xd.DocumentElement.Name, null, ctx);

                    using (MemoryStream msAsm = new MemoryStream())
                    {
                        xd.Save(msAsm);

                        using (MemoryStream msRead = new MemoryStream(
                                   msAsm.ToArray(), false))
                        {
                            tConfig = (AppConfigEx)xmlSerial.Deserialize(msRead);
                        }
                    }
                }
                catch (FileNotFoundException) { }
                catch (Exception) { Debug.Assert(false); }
            }

            if (tConfig != null)
            {
                tConfig.OnLoad();
            }

            return(tConfig);
        }
Esempio n. 17
0
        private bool ExportEx(PwExportInfo pwExportInfo, Stream sOutput,
                              IStatusLogger slLogger, string strXslFile)
        {
            XslCompiledTransform xsl = new XslCompiledTransform();

            try { xsl.Load(strXslFile); }
            catch (Exception exXsl)
            {
                throw new NotSupportedException(strXslFile + StrUtil.NewParagraph +
                                                KPRes.NoXslFile + StrUtil.NewParagraph + exXsl.Message);
            }

            byte[] pbData;
            using (MemoryStream ms = new MemoryStream())
            {
                PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());
                KdbxFile   f  = new KdbxFile(pd);
                f.Save(ms, pwExportInfo.DataGroup, KdbxFormat.PlainXml, slLogger);

                pbData = ms.ToArray();
            }
            if (pbData == null)
            {
                throw new OutOfMemoryException();
            }

            XmlWriterSettings xws = xsl.OutputSettings;

            if (xws == null)
            {
                xws = new XmlWriterSettings();

                xws.CheckCharacters  = false;
                xws.ConformanceLevel = ConformanceLevel.Auto;
                xws.Encoding         = StrUtil.Utf8;
                // xws.Indent = false;
                xws.IndentChars        = "\t";
                xws.NewLineChars       = StrUtil.NewLine;
                xws.NewLineHandling    = NewLineHandling.None;
                xws.OmitXmlDeclaration = true;
            }

            using (MemoryStream msIn = new MemoryStream(pbData, false))
            {
                using (XmlReader xrIn = XmlUtilEx.CreateXmlReader(msIn))
                {
                    using (XmlWriter xwOut = XmlWriter.Create(sOutput, xws))
                    {
                        xsl.Transform(xrIn, xwOut);
                    }
                }
            }

            MemUtil.ZeroByteArray(pbData);
            return(true);
        }
Esempio n. 18
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            using (XmlReader xr = XmlUtilEx.CreateXmlReader(sInput))
            {
                XPathDocument  xpDoc = new XPathDocument(xr);
                XPathNavigator xpNav = xpDoc.CreateNavigator();

                ImportLogins(xpNav, pwStorage);
                ImportMemos(xpNav, pwStorage);
            }
        }
		public static string SafeSerialize(string[] args)
		{
			if(args == null) throw new ArgumentNullException("args");

			string strSerialized = null;
			using(MemoryStream ms = new MemoryStream())
			{
				XmlUtilEx.Serialize<string[]>(ms, args);
				strSerialized = Convert.ToBase64String(ms.ToArray(),
					Base64FormattingOptions.None);
			}

			return strSerialized;
		}
Esempio n. 20
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
            }
        }
Esempio n. 21
0
        private static void Load(string strFilePath, PlgxPluginInfo plgxOutInfo)
        {
            if (strFilePath == null)
            {
                throw new ArgumentNullException("strFilePath");
            }

            plgxOutInfo.CsprojFilePath = strFilePath;

            XmlDocument doc = XmlUtilEx.CreateXmlDocument();

            doc.Load(strFilePath);

            ReadProject(doc.DocumentElement, plgxOutInfo);
        }
Esempio n. 22
0
    public override byte[] GetKey(KeyProviderQueryContext ctx)
    {
        if (ctx == null)
        {
            throw new ArgumentNullException(nameof(ctx));
        }

        // The key file is expected to be next to the database by default:
        var keyFilePath = UrlUtil.StripExtension(ctx.DatabasePath) + DefaultKeyExtension;

        CertificateShortcutProviderKey cspKey;

        if (ctx.CreatingNewKey)
        {
            // Always return null, so that it's not possible to accidentally create a composite key with this provider.
            MessageBox.Show("Certificate Shortcut Provider uses the encrypted master key to access the database. There is no initialization needed other than the master key.\n\nUse 'Options > Initialize Certificate Shortcut Provider...' from the menu to create the encrypted master key.", Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return(null);
        }
        else
        {
            // We need to load an existing key file...

            while (!File.Exists(keyFilePath))
            {
                var ofd = new OpenFileDialogEx("Select your Certificate Shortcut Provider Key file.")
                {
                    Filter = $"Certificate Shortcut Provider Key files (*{DefaultKeyExtension})|*{DefaultKeyExtension}|All files (*.*)|*.*"
                };
                if (ofd.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }
                else
                {
                    keyFilePath = ofd.FileName;
                }
            }

            using (var fs = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))
            {
                cspKey = XmlUtilEx.Deserialize <CertificateShortcutProviderKey>(fs);
            }

            var secretKey = CryptoHelpers.DecryptPassphrase(cspKey);

            return(secretKey.ReadData());
        }
    }
		public static string[] SafeDeserialize(string str)
		{
			if(str == null) throw new ArgumentNullException("str");

			try
			{
				byte[] pb = Convert.FromBase64String(str);
				using(MemoryStream ms = new MemoryStream(pb, false))
				{
					return XmlUtilEx.Deserialize<string[]>(ms);
				}
			}
			catch(Exception) { Debug.Assert(false); }

			return null;
		}