diff --git a/src/KeePassLib2Android/Collections/AutoTypeConfig.cs b/src/KeePassLib2Android/Collections/AutoTypeConfig.cs index b8254e5d..8df14ce5 100644 --- a/src/KeePassLib2Android/Collections/AutoTypeConfig.cs +++ b/src/KeePassLib2Android/Collections/AutoTypeConfig.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -194,13 +194,6 @@ namespace KeePassLib.Collections return true; } - public void Add(AutoTypeAssociation a) - { - Debug.Assert(a != null); if(a == null) throw new ArgumentNullException("a"); - - m_lWindowAssocs.Add(a); - } - public AutoTypeAssociation GetAt(int iIndex) { if((iIndex < 0) || (iIndex >= m_lWindowAssocs.Count)) @@ -209,6 +202,22 @@ namespace KeePassLib.Collections return m_lWindowAssocs[iIndex]; } + public void Add(AutoTypeAssociation a) + { + if(a == null) { Debug.Assert(false); throw new ArgumentNullException("a"); } + + m_lWindowAssocs.Add(a); + } + + public void Insert(int iIndex, AutoTypeAssociation a) + { + if((iIndex < 0) || (iIndex > m_lWindowAssocs.Count)) + throw new ArgumentOutOfRangeException("iIndex"); + if(a == null) { Debug.Assert(false); throw new ArgumentNullException("a"); } + + m_lWindowAssocs.Insert(iIndex, a); + } + public void RemoveAt(int iIndex) { if((iIndex < 0) || (iIndex >= m_lWindowAssocs.Count)) @@ -216,5 +225,20 @@ namespace KeePassLib.Collections m_lWindowAssocs.RemoveAt(iIndex); } + + // public void Sort() + // { + // m_lWindowAssocs.Sort(AutoTypeConfig.AssocCompareFn); + // } + + // private static int AssocCompareFn(AutoTypeAssociation x, + // AutoTypeAssociation y) + // { + // if(x == null) { Debug.Assert(false); return ((y == null) ? 0 : -1); } + // if(y == null) { Debug.Assert(false); return 1; } + // int cn = x.WindowName.CompareTo(y.WindowName); + // if(cn != 0) return cn; + // return x.Sequence.CompareTo(y.Sequence); + // } } } diff --git a/src/KeePassLib2Android/Collections/ProtectedBinaryDictionary.cs b/src/KeePassLib2Android/Collections/ProtectedBinaryDictionary.cs index 8dbb8a5f..3b2e4556 100644 --- a/src/KeePassLib2Android/Collections/ProtectedBinaryDictionary.cs +++ b/src/KeePassLib2Android/Collections/ProtectedBinaryDictionary.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -25,7 +25,6 @@ using System.Diagnostics; using KeePassLib.Interfaces; using KeePassLib.Security; -using KeePassLib.Utility; #if KeePassLibSD using KeePassLibSD; diff --git a/src/KeePassLib2Android/Collections/ProtectedStringDictionary.cs b/src/KeePassLib2Android/Collections/ProtectedStringDictionary.cs index 3248bed0..eb34b016 100644 --- a/src/KeePassLib2Android/Collections/ProtectedStringDictionary.cs +++ b/src/KeePassLib2Android/Collections/ProtectedStringDictionary.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -284,11 +284,7 @@ namespace KeePassLib.Collections public List GetKeys() { - List v = new List(); - - foreach(string strKey in m_vStrings.Keys) v.Add(strKey); - - return v; + return new List(m_vStrings.Keys); } public void EnableProtection(string strField, bool bProtect) @@ -300,7 +296,8 @@ namespace KeePassLib.Collections { byte[] pbData = ps.ReadUtf8(); Set(strField, new ProtectedString(bProtect, pbData)); - MemUtil.ZeroByteArray(pbData); + + if(bProtect) MemUtil.ZeroByteArray(pbData); } } } diff --git a/src/KeePassLib2Android/Collections/PwObjectList.cs b/src/KeePassLib2Android/Collections/PwObjectList.cs index 4f324a5a..f18466cb 100644 --- a/src/KeePassLib2Android/Collections/PwObjectList.cs +++ b/src/KeePassLib2Android/Collections/PwObjectList.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -233,7 +233,7 @@ namespace KeePassLib.Collections if(nCount <= 1) return; int nIndex = m_vObjects.IndexOf(tObject); - Debug.Assert(nIndex >= 0); + if(nIndex < 0) { Debug.Assert(false); return; } if(bUp && (nIndex > 0)) // No assert for top item { @@ -249,6 +249,68 @@ namespace KeePassLib.Collections } } + public void MoveOne(T[] vObjects, bool bUp) + { + Debug.Assert(vObjects != null); + if(vObjects == null) throw new ArgumentNullException("vObjects"); + /// + List lIndices = new List(); + foreach(T t in vObjects) + { + if(t == null) { Debug.Assert(false); continue; } + /// Move some of the objects in this list to the top/bottom. + int p = IndexOf(t); + if(p >= 0) lIndices.Add(p); + else { Debug.Assert(false); } + } + /// + MoveOne(lIndices.ToArray(), bUp); + } + /// List of objects to be moved. + public void MoveOne(int[] vIndices, bool bUp) + { + Debug.Assert(vIndices != null); + if(vIndices == null) throw new ArgumentNullException("vIndices"); + /// Move to top. If false, move to bottom. + int n = m_vObjects.Count; + if(n <= 1) return; // No moving possible + + int m = vIndices.Length; + if(m == 0) return; // Nothing to move + + int[] v = new int[m]; + Array.Copy(vIndices, v, m); + Array.Sort(v); + + if((bUp && (v[0] <= 0)) || (!bUp && (v[m - 1] >= (n - 1)))) + return; // Moving as a block is not possible + + int iStart = (bUp ? 0 : (m - 1)); + int iExcl = (bUp ? m : -1); + int iStep = (bUp ? 1 : -1); + + for(int i = iStart; i != iExcl; i += iStep) + { + int p = v[i]; + if((p < 0) || (p >= n)) { Debug.Assert(false); continue; } + + T t = m_vObjects[p]; + + if(bUp) + { + Debug.Assert(p > 0); + m_vObjects.RemoveAt(p); + m_vObjects.Insert(p - 1, t); + } + else // Down + { + Debug.Assert(p < (n - 1)); + m_vObjects.RemoveAt(p); + m_vObjects.Insert(p + 1, t); + } + } + } + /// /// Move some of the objects in this list to the top/bottom. /// diff --git a/src/KeePassLib2Android/Collections/PwObjectPool.cs b/src/KeePassLib2Android/Collections/PwObjectPool.cs index df37f524..deb05f9b 100644 --- a/src/KeePassLib2Android/Collections/PwObjectPool.cs +++ b/src/KeePassLib2Android/Collections/PwObjectPool.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,6 +18,7 @@ */ using System; +using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; @@ -77,4 +78,154 @@ namespace KeePassLib.Collections return true; } } + + internal sealed class PwObjectPoolEx + { + private Dictionary m_dUuidToId = + new Dictionary(); + private Dictionary m_dIdToItem = + new Dictionary(); + + private PwObjectPoolEx() + { +} + + public static PwObjectPoolEx FromGroup(PwGroup pg) + { + PwObjectPoolEx p = new PwObjectPoolEx(); + + if(pg == null) { Debug.Assert(false); return p; } + + ulong uFreeId = 2; // 0 = "not found", 1 is a hole + + p.m_dUuidToId[pg.Uuid] = uFreeId; + p.m_dIdToItem[uFreeId] = pg; + uFreeId += 2; // Make hole + + p.AddGroupRec(pg, ref uFreeId); + return p; + } + + private void AddGroupRec(PwGroup pg, ref ulong uFreeId) + { + if(pg == null) { Debug.Assert(false); return; } + + ulong uId = uFreeId; + + // Consecutive entries must have consecutive IDs + foreach(PwEntry pe in pg.Entries) + { + Debug.Assert(!m_dUuidToId.ContainsKey(pe.Uuid)); + Debug.Assert(!m_dIdToItem.ContainsValue(pe)); + + m_dUuidToId[pe.Uuid] = uId; + m_dIdToItem[uId] = pe; + ++uId; + } + ++uId; // Make hole + + // Consecutive groups must have consecutive IDs + foreach(PwGroup pgSub in pg.Groups) + { + Debug.Assert(!m_dUuidToId.ContainsKey(pgSub.Uuid)); + Debug.Assert(!m_dIdToItem.ContainsValue(pgSub)); + + m_dUuidToId[pgSub.Uuid] = uId; + m_dIdToItem[uId] = pgSub; + ++uId; + } + ++uId; // Make hole + + foreach(PwGroup pgSub in pg.Groups) + { + AddGroupRec(pgSub, ref uId); + } + + uFreeId = uId; + } + + public ulong GetIdByUuid(PwUuid pwUuid) + { + if(pwUuid == null) { Debug.Assert(false); return 0; } + + ulong uId; + m_dUuidToId.TryGetValue(pwUuid, out uId); + return uId; + } + + public IStructureItem GetItemByUuid(PwUuid pwUuid) + { + if(pwUuid == null) { Debug.Assert(false); return null; } + + ulong uId; + if(!m_dUuidToId.TryGetValue(pwUuid, out uId)) return null; + Debug.Assert(uId != 0); + + return GetItemById(uId); + } + + public IStructureItem GetItemById(ulong uId) + { + IStructureItem p; + m_dIdToItem.TryGetValue(uId, out p); + return p; + } + } + + internal sealed class PwObjectBlock : IEnumerable + where T : class, ITimeLogger, IStructureItem, IDeepCloneable + { + private List m_l = new List(); + + public T PrimaryItem + { + get { return ((m_l.Count > 0) ? m_l[0] : null); } + } + + private DateTime m_dtLocationChanged = DateTime.MinValue; + public DateTime LocationChanged + { + get { return m_dtLocationChanged; } + } + + private PwObjectPoolEx m_poolAssoc = null; + public PwObjectPoolEx PoolAssoc + { + get { return m_poolAssoc; } + } + + public PwObjectBlock() + { + } + +#if DEBUG + public override string ToString() + { + return ("PwObjectBlock, Count = " + m_l.Count.ToString()); + } +#endif + + IEnumerator IEnumerable.GetEnumerator() + { + return m_l.GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return m_l.GetEnumerator(); + } + + public void Add(T t, DateTime dtLoc, PwObjectPoolEx pool) + { + if(t == null) { Debug.Assert(false); return; } + + m_l.Add(t); + + if(dtLoc > m_dtLocationChanged) + { + m_dtLocationChanged = dtLoc; + m_poolAssoc = pool; + } + } + } } diff --git a/src/KeePassLib2Android/Collections/StringDictionaryEx.cs b/src/KeePassLib2Android/Collections/StringDictionaryEx.cs index 15f57724..4a1b07ca 100644 --- a/src/KeePassLib2Android/Collections/StringDictionaryEx.cs +++ b/src/KeePassLib2Android/Collections/StringDictionaryEx.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -32,14 +32,14 @@ using KeePassLibSD; namespace KeePassLib.Collections { public sealed class StringDictionaryEx : IDeepCloneable, - IEnumerable> + IEnumerable>, IEquatable { - private SortedDictionary m_vDict = + private SortedDictionary m_dict = new SortedDictionary(); public int Count { - get { return m_vDict.Count; } + get { return m_dict.Count; } } public StringDictionaryEx() @@ -48,39 +48,53 @@ namespace KeePassLib.Collections IEnumerator IEnumerable.GetEnumerator() { - return m_vDict.GetEnumerator(); + return m_dict.GetEnumerator(); } public IEnumerator> GetEnumerator() { - return m_vDict.GetEnumerator(); + return m_dict.GetEnumerator(); } public StringDictionaryEx CloneDeep() { - StringDictionaryEx plNew = new StringDictionaryEx(); + StringDictionaryEx sdNew = new StringDictionaryEx(); - foreach(KeyValuePair kvpStr in m_vDict) - plNew.Set(kvpStr.Key, kvpStr.Value); + foreach(KeyValuePair kvp in m_dict) + sdNew.m_dict[kvp.Key] = kvp.Value; // Strings are immutable - return plNew; + return sdNew; + } + + public bool Equals(StringDictionaryEx sdOther) + { + if(sdOther == null) { Debug.Assert(false); return false; } + + if(m_dict.Count != sdOther.m_dict.Count) return false; + + foreach(KeyValuePair kvp in sdOther.m_dict) + { + string str = Get(kvp.Key); + if((str == null) || (str != kvp.Value)) return false; + } + + return true; } public string Get(string strName) { - Debug.Assert(strName != null); if(strName == null) throw new ArgumentNullException("strName"); + if(strName == null) { Debug.Assert(false); throw new ArgumentNullException("strName"); } string s; - if(m_vDict.TryGetValue(strName, out s)) return s; - + if(m_dict.TryGetValue(strName, out s)) return s; return null; } public bool Exists(string strName) { - Debug.Assert(strName != null); if(strName == null) throw new ArgumentNullException("strName"); + if(strName == null) { Debug.Assert(false); throw new ArgumentNullException("strName"); } - return m_vDict.ContainsKey(strName); + return m_dict.ContainsKey(strName); } /// @@ -92,10 +106,10 @@ namespace KeePassLib.Collections /// parameters is null. public void Set(string strField, string strNewValue) { - Debug.Assert(strField != null); if(strField == null) throw new ArgumentNullException("strField"); - Debug.Assert(strNewValue != null); if(strNewValue == null) throw new ArgumentNullException("strNewValue"); + if(strField == null) { Debug.Assert(false); throw new ArgumentNullException("strField"); } + if(strNewValue == null) { Debug.Assert(false); throw new ArgumentNullException("strNewValue"); } - m_vDict[strField] = strNewValue; + m_dict[strField] = strNewValue; } /// @@ -108,9 +122,9 @@ namespace KeePassLib.Collections /// parameter is null. public bool Remove(string strField) { - Debug.Assert(strField != null); if(strField == null) throw new ArgumentNullException("strField"); + if(strField == null) { Debug.Assert(false); throw new ArgumentNullException("strField"); } - return m_vDict.Remove(strField); + return m_dict.Remove(strField); } } } diff --git a/src/KeePassLib2Android/Collections/VariantDictionary.cs b/src/KeePassLib2Android/Collections/VariantDictionary.cs new file mode 100644 index 00000000..8aa5a48c --- /dev/null +++ b/src/KeePassLib2Android/Collections/VariantDictionary.cs @@ -0,0 +1,415 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; + +using KeePassLib.Resources; +using KeePassLib.Utility; + +namespace KeePassLib.Collections +{ + public class VariantDictionary : ICloneable + { + private const ushort VdVersion = 0x0100; + private const ushort VdmCritical = 0xFF00; + private const ushort VdmInfo = 0x00FF; + + private Dictionary m_d = new Dictionary(); + + private enum VdType : byte + { + None = 0, + + // Byte = 0x02, + // UInt16 = 0x03, + UInt32 = 0x04, + UInt64 = 0x05, + + // Signed mask: 0x08 + Bool = 0x08, + // SByte = 0x0A, + // Int16 = 0x0B, + Int32 = 0x0C, + Int64 = 0x0D, + + // Float = 0x10, + // Double = 0x11, + // Decimal = 0x12, + + // Char = 0x17, // 16-bit Unicode character + String = 0x18, + + // Array mask: 0x40 + ByteArray = 0x42 + } + + public int Count + { + get { return m_d.Count; } + } + + public VariantDictionary() + { + Debug.Assert((VdmCritical & VdmInfo) == ushort.MinValue); + Debug.Assert((VdmCritical | VdmInfo) == ushort.MaxValue); + } + + private bool Get(string strName, out T t) + { + t = default(T); + + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return false; } + + object o; + if(!m_d.TryGetValue(strName, out o)) return false; // No assert + + if(o == null) { Debug.Assert(false); return false; } + if(o.GetType() != typeof(T)) { Debug.Assert(false); return false; } + + t = (T)o; + return true; + } + + private void SetStruct(string strName, T t) + where T : struct + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return; } + +#if DEBUG + T tEx; + Get(strName, out tEx); // Assert same type +#endif + + m_d[strName] = t; + } + + private void SetRef(string strName, T t) + where T : class + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return; } + if(t == null) { Debug.Assert(false); return; } + +#if DEBUG + T tEx; + Get(strName, out tEx); // Assert same type +#endif + + m_d[strName] = t; + } + + public bool Remove(string strName) + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return false; } + + return m_d.Remove(strName); + } + + public void CopyTo(VariantDictionary d) + { + if(d == null) { Debug.Assert(false); return; } + + // Do not clear the target + foreach(KeyValuePair kvp in m_d) + { + d.m_d[kvp.Key] = kvp.Value; + } + } + + public Type GetTypeOf(string strName) + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return null; } + + object o; + m_d.TryGetValue(strName, out o); + if(o == null) return null; // No assert + + return o.GetType(); + } + + public uint GetUInt32(string strName, uint uDefault) + { + uint u; + if(Get(strName, out u)) return u; + return uDefault; + } + + public void SetUInt32(string strName, uint uValue) + { + SetStruct(strName, uValue); + } + + public ulong GetUInt64(string strName, ulong uDefault) + { + ulong u; + if(Get(strName, out u)) return u; + return uDefault; + } + + public void SetUInt64(string strName, ulong uValue) + { + SetStruct(strName, uValue); + } + + public bool GetBool(string strName, bool bDefault) + { + bool b; + if(Get(strName, out b)) return b; + return bDefault; + } + + public void SetBool(string strName, bool bValue) + { + SetStruct(strName, bValue); + } + + public int GetInt32(string strName, int iDefault) + { + int i; + if(Get(strName, out i)) return i; + return iDefault; + } + + public void SetInt32(string strName, int iValue) + { + SetStruct(strName, iValue); + } + + public long GetInt64(string strName, long lDefault) + { + long l; + if(Get(strName, out l)) return l; + return lDefault; + } + + public void SetInt64(string strName, long lValue) + { + SetStruct(strName, lValue); + } + + public string GetString(string strName) + { + string str; + Get(strName, out str); + return str; + } + + public void SetString(string strName, string strValue) + { + SetRef(strName, strValue); + } + + public byte[] GetByteArray(string strName) + { + byte[] pb; + Get(strName, out pb); + return pb; + } + + public void SetByteArray(string strName, byte[] pbValue) + { + SetRef(strName, pbValue); + } + + /// + /// Create a deep copy. + /// + public virtual object Clone() + { + VariantDictionary vdNew = new VariantDictionary(); + + foreach(KeyValuePair kvp in m_d) + { + object o = kvp.Value; + if(o == null) { Debug.Assert(false); continue; } + + Type t = o.GetType(); + if(t == typeof(byte[])) + { + byte[] p = (byte[])o; + byte[] pNew = new byte[p.Length]; + if(p.Length > 0) Array.Copy(p, pNew, p.Length); + + o = pNew; + } + + vdNew.m_d[kvp.Key] = o; + } + + return vdNew; + } + + public static byte[] Serialize(VariantDictionary p) + { + if(p == null) { Debug.Assert(false); return null; } + + byte[] pbRet; + using(MemoryStream ms = new MemoryStream()) + { + MemUtil.Write(ms, MemUtil.UInt16ToBytes(VdVersion)); + + foreach(KeyValuePair kvp in p.m_d) + { + string strName = kvp.Key; + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); continue; } + byte[] pbName = StrUtil.Utf8.GetBytes(strName); + + object o = kvp.Value; + if(o == null) { Debug.Assert(false); continue; } + + Type t = o.GetType(); + VdType vt = VdType.None; + byte[] pbValue = null; + if(t == typeof(uint)) + { + vt = VdType.UInt32; + pbValue = MemUtil.UInt32ToBytes((uint)o); + } + else if(t == typeof(ulong)) + { + vt = VdType.UInt64; + pbValue = MemUtil.UInt64ToBytes((ulong)o); + } + else if(t == typeof(bool)) + { + vt = VdType.Bool; + pbValue = new byte[1]; + pbValue[0] = ((bool)o ? (byte)1 : (byte)0); + } + else if(t == typeof(int)) + { + vt = VdType.Int32; + pbValue = MemUtil.Int32ToBytes((int)o); + } + else if(t == typeof(long)) + { + vt = VdType.Int64; + pbValue = MemUtil.Int64ToBytes((long)o); + } + else if(t == typeof(string)) + { + vt = VdType.String; + pbValue = StrUtil.Utf8.GetBytes((string)o); + } + else if(t == typeof(byte[])) + { + vt = VdType.ByteArray; + pbValue = (byte[])o; + } + else { Debug.Assert(false); continue; } // Unknown type + + ms.WriteByte((byte)vt); + MemUtil.Write(ms, MemUtil.Int32ToBytes(pbName.Length)); + MemUtil.Write(ms, pbName); + MemUtil.Write(ms, MemUtil.Int32ToBytes(pbValue.Length)); + MemUtil.Write(ms, pbValue); + } + + ms.WriteByte((byte)VdType.None); + pbRet = ms.ToArray(); + } + + return pbRet; + } + + public static VariantDictionary Deserialize(byte[] pb) + { + if(pb == null) { Debug.Assert(false); return null; } + + VariantDictionary d = new VariantDictionary(); + using(MemoryStream ms = new MemoryStream(pb, false)) + { + ushort uVersion = MemUtil.BytesToUInt16(MemUtil.Read(ms, 2)); + if((uVersion & VdmCritical) > (VdVersion & VdmCritical)) + throw new FormatException(KLRes.FileNewVerReq); + + while(true) + { + int iType = ms.ReadByte(); + if(iType < 0) throw new EndOfStreamException(KLRes.FileCorrupted); + byte btType = (byte)iType; + if(btType == (byte)VdType.None) break; + + int cbName = MemUtil.BytesToInt32(MemUtil.Read(ms, 4)); + byte[] pbName = MemUtil.Read(ms, cbName); + if(pbName.Length != cbName) + throw new EndOfStreamException(KLRes.FileCorrupted); + string strName = StrUtil.Utf8.GetString(pbName); + + int cbValue = MemUtil.BytesToInt32(MemUtil.Read(ms, 4)); + byte[] pbValue = MemUtil.Read(ms, cbValue); + if(pbValue.Length != cbValue) + throw new EndOfStreamException(KLRes.FileCorrupted); + + switch(btType) + { + case (byte)VdType.UInt32: + if(cbValue == 4) + d.SetUInt32(strName, MemUtil.BytesToUInt32(pbValue)); + else { Debug.Assert(false); } + break; + + case (byte)VdType.UInt64: + if(cbValue == 8) + d.SetUInt64(strName, MemUtil.BytesToUInt64(pbValue)); + else { Debug.Assert(false); } + break; + + case (byte)VdType.Bool: + if(cbValue == 1) + d.SetBool(strName, (pbValue[0] != 0)); + else { Debug.Assert(false); } + break; + + case (byte)VdType.Int32: + if(cbValue == 4) + d.SetInt32(strName, MemUtil.BytesToInt32(pbValue)); + else { Debug.Assert(false); } + break; + + case (byte)VdType.Int64: + if(cbValue == 8) + d.SetInt64(strName, MemUtil.BytesToInt64(pbValue)); + else { Debug.Assert(false); } + break; + + case (byte)VdType.String: + d.SetString(strName, StrUtil.Utf8.GetString(pbValue)); + break; + + case (byte)VdType.ByteArray: + d.SetByteArray(strName, pbValue); + break; + + default: + Debug.Assert(false); // Unknown type + break; + } + } + + Debug.Assert(ms.ReadByte() < 0); + } + + return d; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Cipher.cs b/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Cipher.cs new file mode 100644 index 00000000..ad0c93b4 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Cipher.cs @@ -0,0 +1,251 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +using KeePassLib.Resources; +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.Cipher +{ + /// + /// Implementation of the ChaCha20 cipher with a 96-bit nonce, + /// as specified in RFC 7539. + /// https://tools.ietf.org/html/rfc7539 + /// + public sealed class ChaCha20Cipher : CtrBlockCipher + { + private uint[] m_s = new uint[16]; // State + private uint[] m_x = new uint[16]; // Working buffer + + private bool m_bLargeCounter; // See constructor documentation + + private static readonly uint[] g_sigma = new uint[4] { + 0x61707865, 0x3320646E, 0x79622D32, 0x6B206574 + }; + + private const string StrNameRfc = "ChaCha20 (RFC 7539)"; + + public override int BlockSize + { + get { return 64; } + } + + public ChaCha20Cipher(byte[] pbKey32, byte[] pbIV12) : + this(pbKey32, pbIV12, false) + { + } + + /// + /// Constructor. + /// + /// Key (32 bytes). + /// Nonce (12 bytes). + /// If false, the RFC 7539 version + /// of ChaCha20 is used. In this case, only 256 GB of data can be + /// encrypted securely (because the block counter is a 32-bit variable); + /// an attempt to encrypt more data throws an exception. + /// If is true, the 32-bit + /// counter overflows to another 32-bit variable (i.e. the counter + /// effectively is a 64-bit variable), like in the original ChaCha20 + /// specification by D. J. Bernstein (which has a 64-bit counter and a + /// 64-bit nonce). To be compatible with this version, the 64-bit nonce + /// must be stored in the last 8 bytes of + /// and the first 4 bytes must be 0. + /// If the IV was generated randomly, a 12-byte IV and a large counter + /// can be used to securely encrypt more than 256 GB of data (but note + /// this is incompatible with RFC 7539 and the original specification). + public ChaCha20Cipher(byte[] pbKey32, byte[] pbIV12, bool bLargeCounter) : + base() + { + if(pbKey32 == null) throw new ArgumentNullException("pbKey32"); + if(pbKey32.Length != 32) throw new ArgumentOutOfRangeException("pbKey32"); + if(pbIV12 == null) throw new ArgumentNullException("pbIV12"); + if(pbIV12.Length != 12) throw new ArgumentOutOfRangeException("pbIV12"); + + m_bLargeCounter = bLargeCounter; + + // Key setup + m_s[4] = MemUtil.BytesToUInt32(pbKey32, 0); + m_s[5] = MemUtil.BytesToUInt32(pbKey32, 4); + m_s[6] = MemUtil.BytesToUInt32(pbKey32, 8); + m_s[7] = MemUtil.BytesToUInt32(pbKey32, 12); + m_s[8] = MemUtil.BytesToUInt32(pbKey32, 16); + m_s[9] = MemUtil.BytesToUInt32(pbKey32, 20); + m_s[10] = MemUtil.BytesToUInt32(pbKey32, 24); + m_s[11] = MemUtil.BytesToUInt32(pbKey32, 28); + m_s[0] = g_sigma[0]; + m_s[1] = g_sigma[1]; + m_s[2] = g_sigma[2]; + m_s[3] = g_sigma[3]; + + // IV setup + m_s[12] = 0; // Counter + m_s[13] = MemUtil.BytesToUInt32(pbIV12, 0); + m_s[14] = MemUtil.BytesToUInt32(pbIV12, 4); + m_s[15] = MemUtil.BytesToUInt32(pbIV12, 8); + } + + protected override void Dispose(bool bDisposing) + { + MemUtil.ZeroArray(m_s); + MemUtil.ZeroArray(m_x); + + base.Dispose(bDisposing); + } + + protected override void NextBlock(byte[] pBlock) + { + if(pBlock == null) throw new ArgumentNullException("pBlock"); + if(pBlock.Length != 64) throw new ArgumentOutOfRangeException("pBlock"); + + // x is a local alias for the working buffer; with this, + // the compiler/runtime might remove some checks + uint[] x = m_x; + if(x == null) throw new InvalidOperationException(); + if(x.Length < 16) throw new InvalidOperationException(); + + uint[] s = m_s; + if(s == null) throw new InvalidOperationException(); + if(s.Length < 16) throw new InvalidOperationException(); + + Array.Copy(s, x, 16); + + unchecked + { + // 10 * 8 quarter rounds = 20 rounds + for(int i = 0; i < 10; ++i) + { + // Column quarter rounds + x[ 0] += x[ 4]; + x[12] = MemUtil.RotateLeft32(x[12] ^ x[ 0], 16); + x[ 8] += x[12]; + x[ 4] = MemUtil.RotateLeft32(x[ 4] ^ x[ 8], 12); + x[ 0] += x[ 4]; + x[12] = MemUtil.RotateLeft32(x[12] ^ x[ 0], 8); + x[ 8] += x[12]; + x[ 4] = MemUtil.RotateLeft32(x[ 4] ^ x[ 8], 7); + + x[ 1] += x[ 5]; + x[13] = MemUtil.RotateLeft32(x[13] ^ x[ 1], 16); + x[ 9] += x[13]; + x[ 5] = MemUtil.RotateLeft32(x[ 5] ^ x[ 9], 12); + x[ 1] += x[ 5]; + x[13] = MemUtil.RotateLeft32(x[13] ^ x[ 1], 8); + x[ 9] += x[13]; + x[ 5] = MemUtil.RotateLeft32(x[ 5] ^ x[ 9], 7); + + x[ 2] += x[ 6]; + x[14] = MemUtil.RotateLeft32(x[14] ^ x[ 2], 16); + x[10] += x[14]; + x[ 6] = MemUtil.RotateLeft32(x[ 6] ^ x[10], 12); + x[ 2] += x[ 6]; + x[14] = MemUtil.RotateLeft32(x[14] ^ x[ 2], 8); + x[10] += x[14]; + x[ 6] = MemUtil.RotateLeft32(x[ 6] ^ x[10], 7); + + x[ 3] += x[ 7]; + x[15] = MemUtil.RotateLeft32(x[15] ^ x[ 3], 16); + x[11] += x[15]; + x[ 7] = MemUtil.RotateLeft32(x[ 7] ^ x[11], 12); + x[ 3] += x[ 7]; + x[15] = MemUtil.RotateLeft32(x[15] ^ x[ 3], 8); + x[11] += x[15]; + x[ 7] = MemUtil.RotateLeft32(x[ 7] ^ x[11], 7); + + // Diagonal quarter rounds + x[ 0] += x[ 5]; + x[15] = MemUtil.RotateLeft32(x[15] ^ x[ 0], 16); + x[10] += x[15]; + x[ 5] = MemUtil.RotateLeft32(x[ 5] ^ x[10], 12); + x[ 0] += x[ 5]; + x[15] = MemUtil.RotateLeft32(x[15] ^ x[ 0], 8); + x[10] += x[15]; + x[ 5] = MemUtil.RotateLeft32(x[ 5] ^ x[10], 7); + + x[ 1] += x[ 6]; + x[12] = MemUtil.RotateLeft32(x[12] ^ x[ 1], 16); + x[11] += x[12]; + x[ 6] = MemUtil.RotateLeft32(x[ 6] ^ x[11], 12); + x[ 1] += x[ 6]; + x[12] = MemUtil.RotateLeft32(x[12] ^ x[ 1], 8); + x[11] += x[12]; + x[ 6] = MemUtil.RotateLeft32(x[ 6] ^ x[11], 7); + + x[ 2] += x[ 7]; + x[13] = MemUtil.RotateLeft32(x[13] ^ x[ 2], 16); + x[ 8] += x[13]; + x[ 7] = MemUtil.RotateLeft32(x[ 7] ^ x[ 8], 12); + x[ 2] += x[ 7]; + x[13] = MemUtil.RotateLeft32(x[13] ^ x[ 2], 8); + x[ 8] += x[13]; + x[ 7] = MemUtil.RotateLeft32(x[ 7] ^ x[ 8], 7); + + x[ 3] += x[ 4]; + x[14] = MemUtil.RotateLeft32(x[14] ^ x[ 3], 16); + x[ 9] += x[14]; + x[ 4] = MemUtil.RotateLeft32(x[ 4] ^ x[ 9], 12); + x[ 3] += x[ 4]; + x[14] = MemUtil.RotateLeft32(x[14] ^ x[ 3], 8); + x[ 9] += x[14]; + x[ 4] = MemUtil.RotateLeft32(x[ 4] ^ x[ 9], 7); + } + + for(int i = 0; i < 16; ++i) x[i] += s[i]; + + for(int i = 0; i < 16; ++i) + { + int i4 = i << 2; + uint xi = x[i]; + + pBlock[i4] = (byte)xi; + pBlock[i4 + 1] = (byte)(xi >> 8); + pBlock[i4 + 2] = (byte)(xi >> 16); + pBlock[i4 + 3] = (byte)(xi >> 24); + } + + ++s[12]; + if(s[12] == 0) + { + if(!m_bLargeCounter) + throw new InvalidOperationException( + KLRes.EncDataTooLarge.Replace(@"{PARAM}", StrNameRfc)); + ++s[13]; // Increment high half of large counter + } + } + } + + public long Seek(long lOffset, SeekOrigin so) + { + if(so != SeekOrigin.Begin) throw new NotSupportedException(); + + if((lOffset < 0) || ((lOffset & 63) != 0) || + ((lOffset >> 6) > (long)uint.MaxValue)) + throw new ArgumentOutOfRangeException("lOffset"); + + m_s[12] = (uint)(lOffset >> 6); + InvalidateBlock(); + + return lOffset; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Engine.cs b/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Engine.cs new file mode 100644 index 00000000..2fa6fe1d --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/Cipher/ChaCha20Engine.cs @@ -0,0 +1,174 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; + +using KeePassLib.Resources; + +namespace KeePassLib.Cryptography.Cipher +{ + public sealed class ChaCha20Engine : ICipherEngine2 + { + private PwUuid m_uuid = new PwUuid(new byte[] { + 0xD6, 0x03, 0x8A, 0x2B, 0x8B, 0x6F, 0x4C, 0xB5, + 0xA5, 0x24, 0x33, 0x9A, 0x31, 0xDB, 0xB5, 0x9A + }); + + public PwUuid CipherUuid + { + get { return m_uuid; } + } + + public string DisplayName + { + get + { + return ("ChaCha20 (" + KLRes.KeyBits.Replace(@"{PARAM}", + "256") + ", RFC 7539)"); + } + } + + public int KeyLength + { + get { return 32; } + } + + public int IVLength + { + get { return 12; } // 96 bits + } + + public Stream EncryptStream(Stream sPlainText, byte[] pbKey, byte[] pbIV) + { + return new ChaCha20Stream(sPlainText, true, pbKey, pbIV); + } + + public Stream DecryptStream(Stream sEncrypted, byte[] pbKey, byte[] pbIV) + { + return new ChaCha20Stream(sEncrypted, false, pbKey, pbIV); + } + } + + internal sealed class ChaCha20Stream : Stream + { + private Stream m_sBase; + private readonly bool m_bWriting; + private ChaCha20Cipher m_c; + + private byte[] m_pbBuffer = null; + + public override bool CanRead + { + get { return !m_bWriting; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return m_bWriting; } + } + + public override long Length + { + get { Debug.Assert(false); throw new NotSupportedException(); } + } + + public override long Position + { + get { Debug.Assert(false); throw new NotSupportedException(); } + set { Debug.Assert(false); throw new NotSupportedException(); } + } + + public ChaCha20Stream(Stream sBase, bool bWriting, byte[] pbKey32, + byte[] pbIV12) + { + if(sBase == null) throw new ArgumentNullException("sBase"); + + m_sBase = sBase; + m_bWriting = bWriting; + m_c = new ChaCha20Cipher(pbKey32, pbIV12); + } + + protected override void Dispose(bool bDisposing) + { + if(!bDisposing) return; + + if(m_sBase != null) + { + m_c.Dispose(); + m_c = null; + + m_sBase.Close(); + m_sBase = null; + } + + m_pbBuffer = null; + } + + public override void Flush() + { + Debug.Assert(m_sBase != null); + if(m_bWriting && (m_sBase != null)) m_sBase.Flush(); + } + + public override long Seek(long lOffset, SeekOrigin soOrigin) + { + Debug.Assert(false); + throw new NotImplementedException(); + } + + public override void SetLength(long lValue) + { + Debug.Assert(false); + throw new NotImplementedException(); + } + + public override int Read(byte[] pbBuffer, int iOffset, int nCount) + { + if(m_bWriting) throw new InvalidOperationException(); + + int cbRead = m_sBase.Read(pbBuffer, iOffset, nCount); + m_c.Decrypt(pbBuffer, iOffset, cbRead); + return cbRead; + } + + public override void Write(byte[] pbBuffer, int iOffset, int nCount) + { + if(nCount < 0) throw new ArgumentOutOfRangeException("nCount"); + if(nCount == 0) return; + + if(!m_bWriting) throw new InvalidOperationException(); + + if((m_pbBuffer == null) || (m_pbBuffer.Length < nCount)) + m_pbBuffer = new byte[nCount]; + Array.Copy(pbBuffer, iOffset, m_pbBuffer, 0, nCount); + + m_c.Encrypt(m_pbBuffer, 0, nCount); + m_sBase.Write(m_pbBuffer, 0, nCount); + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/Cipher/CipherPool.cs b/src/KeePassLib2Android/Cryptography/Cipher/CipherPool.cs index cda14f64..836a157c 100644 --- a/src/KeePassLib2Android/Cryptography/Cipher/CipherPool.cs +++ b/src/KeePassLib2Android/Cryptography/Cipher/CipherPool.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -22,7 +22,6 @@ using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; -using System.Security; namespace KeePassLib.Cryptography.Cipher { @@ -41,12 +40,17 @@ namespace KeePassLib.Cryptography.Cipher { get { - if(m_poolGlobal != null) return m_poolGlobal; + CipherPool cp = m_poolGlobal; + if(cp == null) + { + cp = new CipherPool(); + cp.AddCipher(new StandardAesEngine()); + cp.AddCipher(new ChaCha20Engine()); - m_poolGlobal = new CipherPool(); - m_poolGlobal.AddCipher(new StandardAesEngine()); + m_poolGlobal = cp; + } - return m_poolGlobal; + return cp; } } diff --git a/src/KeePassLib2Android/Cryptography/Cipher/CtrBlockCipher.cs b/src/KeePassLib2Android/Cryptography/Cipher/CtrBlockCipher.cs new file mode 100644 index 00000000..87ec3daa --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/Cipher/CtrBlockCipher.cs @@ -0,0 +1,101 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.Cipher +{ + public abstract class CtrBlockCipher : IDisposable + { + private byte[] m_pBlock; + private int m_iBlockPos; + + public abstract int BlockSize + { + get; + } + + public CtrBlockCipher() + { + int cb = this.BlockSize; + if(cb <= 0) throw new InvalidOperationException("this.BlockSize"); + + m_pBlock = new byte[cb]; + m_iBlockPos = cb; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool bDisposing) + { + MemUtil.ZeroByteArray(m_pBlock); + m_iBlockPos = m_pBlock.Length; + } + + protected void InvalidateBlock() + { + m_iBlockPos = m_pBlock.Length; + } + + protected abstract void NextBlock(byte[] pBlock); + + public void Encrypt(byte[] m, int iOffset, int cb) + { + if(m == null) throw new ArgumentNullException("m"); + if(iOffset < 0) throw new ArgumentOutOfRangeException("iOffset"); + if(cb < 0) throw new ArgumentOutOfRangeException("cb"); + if(iOffset > (m.Length - cb)) throw new ArgumentOutOfRangeException("cb"); + + int cbBlock = m_pBlock.Length; + + while(cb > 0) + { + Debug.Assert(m_iBlockPos <= cbBlock); + if(m_iBlockPos == cbBlock) + { + NextBlock(m_pBlock); + m_iBlockPos = 0; + } + + int cbCopy = Math.Min(cbBlock - m_iBlockPos, cb); + Debug.Assert(cbCopy > 0); + + MemUtil.XorArray(m_pBlock, m_iBlockPos, m, iOffset, cbCopy); + + m_iBlockPos += cbCopy; + iOffset += cbCopy; + cb -= cbCopy; + } + } + + public void Decrypt(byte[] m, int iOffset, int cb) + { + Encrypt(m, iOffset, cb); + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/Cipher/ICipherEngine.cs b/src/KeePassLib2Android/Cryptography/Cipher/ICipherEngine.cs index c549e54b..f647d3f9 100644 --- a/src/KeePassLib2Android/Cryptography/Cipher/ICipherEngine.cs +++ b/src/KeePassLib2Android/Cryptography/Cipher/ICipherEngine.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -63,4 +63,25 @@ namespace KeePassLib.Cryptography.Cipher /// Stream, from which the decrypted data can be read. Stream DecryptStream(Stream sEncrypted, byte[] pbKey, byte[] pbIV); } + + public interface ICipherEngine2 : ICipherEngine + { + /// + /// Length of an encryption key in bytes. + /// The base ICipherEngine assumes 32. + /// + int KeyLength + { + get; +} + + /// + /// Length of the initialization vector in bytes. + /// The base ICipherEngine assumes 16. + /// + int IVLength + { + get; + } + } } diff --git a/src/KeePassLib2Android/Cryptography/Cipher/Salsa20Cipher.cs b/src/KeePassLib2Android/Cryptography/Cipher/Salsa20Cipher.cs index 884de62c..63d66366 100644 --- a/src/KeePassLib2Android/Cryptography/Cipher/Salsa20Cipher.cs +++ b/src/KeePassLib2Android/Cryptography/Cipher/Salsa20Cipher.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,169 +19,143 @@ // Implementation of the Salsa20 cipher, based on the eSTREAM submission. + using System; +using System.Collections.Generic; using System.Diagnostics; using KeePassLib.Utility; namespace KeePassLib.Cryptography.Cipher { - public sealed class Salsa20Cipher + public sealed class Salsa20Cipher : CtrBlockCipher { - private uint[] m_state = new uint[16]; + private uint[] m_s = new uint[16]; // State private uint[] m_x = new uint[16]; // Working buffer - private byte[] m_output = new byte[64]; - private int m_outputPos = 64; - - private static readonly uint[] m_sigma = new uint[4]{ + private static readonly uint[] g_sigma = new uint[4] { 0x61707865, 0x3320646E, 0x79622D32, 0x6B206574 }; - public Salsa20Cipher(byte[] pbKey32, byte[] pbIV8) + public override int BlockSize { - KeySetup(pbKey32); - IvSetup(pbIV8); + get { return 64; } } - ~Salsa20Cipher() + public Salsa20Cipher(byte[] pbKey32, byte[] pbIV8) : base() { + if(pbKey32 == null) throw new ArgumentNullException("pbKey32"); + if(pbKey32.Length != 32) throw new ArgumentOutOfRangeException("pbKey32"); + if(pbIV8 == null) throw new ArgumentNullException("pbIV8"); + if(pbIV8.Length != 8) throw new ArgumentOutOfRangeException("pbIV8"); // Clear sensitive data - Array.Clear(m_state, 0, m_state.Length); - Array.Clear(m_x, 0, m_x.Length); + // Key setup + m_s[1] = MemUtil.BytesToUInt32(pbKey32, 0); + m_s[2] = MemUtil.BytesToUInt32(pbKey32, 4); + m_s[3] = MemUtil.BytesToUInt32(pbKey32, 8); + m_s[4] = MemUtil.BytesToUInt32(pbKey32, 12); + m_s[11] = MemUtil.BytesToUInt32(pbKey32, 16); + m_s[12] = MemUtil.BytesToUInt32(pbKey32, 20); + m_s[13] = MemUtil.BytesToUInt32(pbKey32, 24); + m_s[14] = MemUtil.BytesToUInt32(pbKey32, 28); + m_s[0] = g_sigma[0]; + m_s[5] = g_sigma[1]; + m_s[10] = g_sigma[2]; + m_s[15] = g_sigma[3]; + + // IV setup + m_s[6] = MemUtil.BytesToUInt32(pbIV8, 0); + m_s[7] = MemUtil.BytesToUInt32(pbIV8, 4); + m_s[8] = 0; // Counter, low + m_s[9] = 0; // Counter, high } - private void NextOutput() + protected override void Dispose(bool bDisposing) { - uint[] x = m_x; // Local alias for working buffer + MemUtil.ZeroArray(m_s); + MemUtil.ZeroArray(m_x); + base.Dispose(bDisposing); + } // Compiler/runtime might remove array bound checks after this + protected override void NextBlock(byte[] pBlock) + { + if(pBlock == null) throw new ArgumentNullException("pBlock"); + if(pBlock.Length != 64) throw new ArgumentOutOfRangeException("pBlock"); + + // x is a local alias for the working buffer; with this, + // the compiler/runtime might remove some checks + uint[] x = m_x; + if(x == null) throw new InvalidOperationException(); if(x.Length < 16) throw new InvalidOperationException(); - Array.Copy(m_state, x, 16); + uint[] s = m_s; + if(s == null) throw new InvalidOperationException(); + if(s.Length < 16) throw new InvalidOperationException(); + + Array.Copy(s, x, 16); unchecked { + // 10 * 8 quarter rounds = 20 rounds for(int i = 0; i < 10; ++i) // (int i = 20; i > 0; i -= 2) { - x[ 4] ^= Rotl32(x[ 0] + x[12], 7); - x[ 8] ^= Rotl32(x[ 4] + x[ 0], 9); - x[12] ^= Rotl32(x[ 8] + x[ 4], 13); - x[ 0] ^= Rotl32(x[12] + x[ 8], 18); - x[ 9] ^= Rotl32(x[ 5] + x[ 1], 7); - x[13] ^= Rotl32(x[ 9] + x[ 5], 9); - x[ 1] ^= Rotl32(x[13] + x[ 9], 13); - x[ 5] ^= Rotl32(x[ 1] + x[13], 18); - x[14] ^= Rotl32(x[10] + x[ 6], 7); - x[ 2] ^= Rotl32(x[14] + x[10], 9); - x[ 6] ^= Rotl32(x[ 2] + x[14], 13); - x[10] ^= Rotl32(x[ 6] + x[ 2], 18); - x[ 3] ^= Rotl32(x[15] + x[11], 7); - x[ 7] ^= Rotl32(x[ 3] + x[15], 9); - x[11] ^= Rotl32(x[ 7] + x[ 3], 13); - x[15] ^= Rotl32(x[11] + x[ 7], 18); - x[ 1] ^= Rotl32(x[ 0] + x[ 3], 7); - x[ 2] ^= Rotl32(x[ 1] + x[ 0], 9); - x[ 3] ^= Rotl32(x[ 2] + x[ 1], 13); - x[ 0] ^= Rotl32(x[ 3] + x[ 2], 18); - x[ 6] ^= Rotl32(x[ 5] + x[ 4], 7); - x[ 7] ^= Rotl32(x[ 6] + x[ 5], 9); - x[ 4] ^= Rotl32(x[ 7] + x[ 6], 13); - x[ 5] ^= Rotl32(x[ 4] + x[ 7], 18); - x[11] ^= Rotl32(x[10] + x[ 9], 7); - x[ 8] ^= Rotl32(x[11] + x[10], 9); - x[ 9] ^= Rotl32(x[ 8] + x[11], 13); - x[10] ^= Rotl32(x[ 9] + x[ 8], 18); - x[12] ^= Rotl32(x[15] + x[14], 7); - x[13] ^= Rotl32(x[12] + x[15], 9); - x[14] ^= Rotl32(x[13] + x[12], 13); - x[15] ^= Rotl32(x[14] + x[13], 18); - } + x[ 4] ^= MemUtil.RotateLeft32(x[ 0] + x[12], 7); + x[ 8] ^= MemUtil.RotateLeft32(x[ 4] + x[ 0], 9); + x[12] ^= MemUtil.RotateLeft32(x[ 8] + x[ 4], 13); + x[ 0] ^= MemUtil.RotateLeft32(x[12] + x[ 8], 18); + + x[ 9] ^= MemUtil.RotateLeft32(x[ 5] + x[ 1], 7); + x[13] ^= MemUtil.RotateLeft32(x[ 9] + x[ 5], 9); + x[ 1] ^= MemUtil.RotateLeft32(x[13] + x[ 9], 13); + x[ 5] ^= MemUtil.RotateLeft32(x[ 1] + x[13], 18); + + x[14] ^= MemUtil.RotateLeft32(x[10] + x[ 6], 7); + x[ 2] ^= MemUtil.RotateLeft32(x[14] + x[10], 9); + x[ 6] ^= MemUtil.RotateLeft32(x[ 2] + x[14], 13); + x[10] ^= MemUtil.RotateLeft32(x[ 6] + x[ 2], 18); + + x[ 3] ^= MemUtil.RotateLeft32(x[15] + x[11], 7); + x[ 7] ^= MemUtil.RotateLeft32(x[ 3] + x[15], 9); + x[11] ^= MemUtil.RotateLeft32(x[ 7] + x[ 3], 13); + x[15] ^= MemUtil.RotateLeft32(x[11] + x[ 7], 18); + + x[ 1] ^= MemUtil.RotateLeft32(x[ 0] + x[ 3], 7); + x[ 2] ^= MemUtil.RotateLeft32(x[ 1] + x[ 0], 9); + x[ 3] ^= MemUtil.RotateLeft32(x[ 2] + x[ 1], 13); + x[ 0] ^= MemUtil.RotateLeft32(x[ 3] + x[ 2], 18); + + x[ 6] ^= MemUtil.RotateLeft32(x[ 5] + x[ 4], 7); + x[ 7] ^= MemUtil.RotateLeft32(x[ 6] + x[ 5], 9); + x[ 4] ^= MemUtil.RotateLeft32(x[ 7] + x[ 6], 13); + x[ 5] ^= MemUtil.RotateLeft32(x[ 4] + x[ 7], 18); + + x[11] ^= MemUtil.RotateLeft32(x[10] + x[ 9], 7); + x[ 8] ^= MemUtil.RotateLeft32(x[11] + x[10], 9); + x[ 9] ^= MemUtil.RotateLeft32(x[ 8] + x[11], 13); + x[10] ^= MemUtil.RotateLeft32(x[ 9] + x[ 8], 18); + + x[12] ^= MemUtil.RotateLeft32(x[15] + x[14], 7); + x[13] ^= MemUtil.RotateLeft32(x[12] + x[15], 9); + x[14] ^= MemUtil.RotateLeft32(x[13] + x[12], 13); + x[15] ^= MemUtil.RotateLeft32(x[14] + x[13], 18); + } + + for(int i = 0; i < 16; ++i) x[i] += s[i]; for(int i = 0; i < 16; ++i) - x[i] += m_state[i]; + { + int i4 = i << 2; + uint xi = x[i]; - for(int i = 0; i < 16; ++i) - { - m_output[i << 2] = (byte)x[i]; - m_output[(i << 2) + 1] = (byte)(x[i] >> 8); - m_output[(i << 2) + 2] = (byte)(x[i] >> 16); - m_output[(i << 2) + 3] = (byte)(x[i] >> 24); - } - - m_outputPos = 0; - ++m_state[8]; - if(m_state[8] == 0) ++m_state[9]; - } + pBlock[i4] = (byte)xi; + pBlock[i4 + 1] = (byte)(xi >> 8); + pBlock[i4 + 2] = (byte)(xi >> 16); + pBlock[i4 + 3] = (byte)(xi >> 24); } - private static uint Rotl32(uint x, int b) - { - unchecked - { - return ((x << b) | (x >> (32 - b))); - } - } - - private static uint U8To32Little(byte[] pb, int iOffset) - { - unchecked - { - return ((uint)pb[iOffset] | ((uint)pb[iOffset + 1] << 8) | - ((uint)pb[iOffset + 2] << 16) | ((uint)pb[iOffset + 3] << 24)); - } - } - - private void KeySetup(byte[] k) - { - if(k == null) throw new ArgumentNullException("k"); - if(k.Length != 32) throw new ArgumentException(); - - m_state[1] = U8To32Little(k, 0); - m_state[2] = U8To32Little(k, 4); - m_state[3] = U8To32Little(k, 8); - m_state[4] = U8To32Little(k, 12); - m_state[11] = U8To32Little(k, 16); - m_state[12] = U8To32Little(k, 20); - m_state[13] = U8To32Little(k, 24); - m_state[14] = U8To32Little(k, 28); - m_state[0] = m_sigma[0]; - m_state[5] = m_sigma[1]; - m_state[10] = m_sigma[2]; - m_state[15] = m_sigma[3]; - } - - private void IvSetup(byte[] pbIV) - { - if(pbIV == null) throw new ArgumentNullException("pbIV"); - if(pbIV.Length != 8) throw new ArgumentException(); - - m_state[6] = U8To32Little(pbIV, 0); - m_state[7] = U8To32Little(pbIV, 4); - m_state[8] = 0; - m_state[9] = 0; - } - - public void Encrypt(byte[] m, int nByteCount, bool bXor) - { - if(m == null) throw new ArgumentNullException("m"); - if(nByteCount > m.Length) throw new ArgumentException(); - - int nBytesRem = nByteCount, nOffset = 0; - while(nBytesRem > 0) - { - Debug.Assert((m_outputPos >= 0) && (m_outputPos <= 64)); - if(m_outputPos == 64) NextOutput(); - Debug.Assert(m_outputPos < 64); - - int nCopy = Math.Min(64 - m_outputPos, nBytesRem); - - if(bXor) MemUtil.XorArray(m_output, m_outputPos, m, nOffset, nCopy); - else Array.Copy(m_output, m_outputPos, m, nOffset, nCopy); - - m_outputPos += nCopy; - nBytesRem -= nCopy; - nOffset += nCopy; + ++s[8]; + if(s[8] == 0) ++s[9]; } } } diff --git a/src/KeePassLib2Android/Cryptography/Cipher/StandardAesEngine.cs b/src/KeePassLib2Android/Cryptography/Cipher/StandardAesEngine.cs index b0b9b7b7..eebd1248 100644 --- a/src/KeePassLib2Android/Cryptography/Cipher/StandardAesEngine.cs +++ b/src/KeePassLib2Android/Cryptography/Cipher/StandardAesEngine.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,15 +24,8 @@ using System.IO; using System.Security; using System.Diagnostics; -#if !KeePassRT +#if !KeePassUAP using System.Security.Cryptography; -#else -using Org.BouncyCastle.Crypto; -using Org.BouncyCastle.Crypto.Engines; -using Org.BouncyCastle.Crypto.IO; -using Org.BouncyCastle.Crypto.Modes; -using Org.BouncyCastle.Crypto.Paddings; -using Org.BouncyCastle.Crypto.Parameters; #endif using KeePassLib.Resources; @@ -44,12 +37,12 @@ namespace KeePassLib.Cryptography.Cipher /// public sealed class StandardAesEngine : ICipherEngine { -#if !KeePassRT +#if !KeePassUAP private const CipherMode m_rCipherMode = CipherMode.CBC; private const PaddingMode m_rCipherPadding = PaddingMode.PKCS7; #endif - private static PwUuid m_uuidAes = null; + private static PwUuid g_uuidAes = null; /// /// UUID of the cipher engine. This ID uniquely identifies the @@ -59,14 +52,16 @@ namespace KeePassLib.Cryptography.Cipher { get { - if(m_uuidAes == null) + PwUuid pu = g_uuidAes; + if(pu == null) { - m_uuidAes = new PwUuid(new byte[]{ + pu = new PwUuid(new byte[] { 0x31, 0xC1, 0xF2, 0xE6, 0xBF, 0x71, 0x43, 0x50, 0xBE, 0x58, 0x05, 0x21, 0x6A, 0xFC, 0x5A, 0xFF }); + g_uuidAes = pu; } - return m_uuidAes; + return pu; } } @@ -81,7 +76,14 @@ namespace KeePassLib.Cryptography.Cipher /// /// Get a displayable name describing this cipher engine. /// - public string DisplayName { get { return KLRes.EncAlgorithmAes; } } + public string DisplayName + { + get + { + return ("AES/Rijndael (" + KLRes.KeyBits.Replace(@"{PARAM}", + "256") + ", FIPS 197)"); + } + } private static void ValidateArguments(Stream stream, bool bEncrypt, byte[] pbKey, byte[] pbIV) { @@ -98,12 +100,12 @@ namespace KeePassLib.Cryptography.Cipher if(bEncrypt) { Debug.Assert(stream.CanWrite); - if(stream.CanWrite == false) throw new ArgumentException("Stream must be writable!"); + if(!stream.CanWrite) throw new ArgumentException("Stream must be writable!"); } else // Decrypt { Debug.Assert(stream.CanRead); - if(stream.CanRead == false) throw new ArgumentException("Encrypted stream must be readable!"); + if(!stream.CanRead) throw new ArgumentException("Encrypted stream must be readable!"); } } @@ -117,7 +119,9 @@ namespace KeePassLib.Cryptography.Cipher byte[] pbLocalKey = new byte[32]; Array.Copy(pbKey, pbLocalKey, 32); -#if !KeePassRT +#if KeePassUAP + return StandardAesEngineExt.CreateStream(s, bEncrypt, pbLocalKey, pbLocalIV); +#else RijndaelManaged r = new RijndaelManaged(); if(r.BlockSize != 128) // AES block size { @@ -137,18 +141,6 @@ namespace KeePassLib.Cryptography.Cipher return new CryptoStream(s, iTransform, bEncrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read); -#else - AesEngine aes = new AesEngine(); - CbcBlockCipher cbc = new CbcBlockCipher(aes); - PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(cbc, - new Pkcs7Padding()); - KeyParameter kp = new KeyParameter(pbLocalKey); - ParametersWithIV prmIV = new ParametersWithIV(kp, pbLocalIV); - bc.Init(bEncrypt, prmIV); - - IBufferedCipher cpRead = (bEncrypt ? null : bc); - IBufferedCipher cpWrite = (bEncrypt ? bc : null); - return new CipherStream(s, cpRead, cpWrite); #endif } diff --git a/src/KeePassLib2Android/Cryptography/CryptoRandom.cs b/src/KeePassLib2Android/Cryptography/CryptoRandom.cs index 9c3dc7c1..d591077c 100644 --- a/src/KeePassLib2Android/Cryptography/CryptoRandom.cs +++ b/src/KeePassLib2Android/Cryptography/CryptoRandom.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll @@ -20,11 +20,13 @@ */ using System; -using System.Security; -using System.Security.Cryptography; -using System.IO; using System.Diagnostics; +using System.IO; + +#if !KeePassUAP using System.Drawing; +using System.Security.Cryptography; +#endif using KeePassLib.Native; using KeePassLib.Utility; @@ -39,21 +41,30 @@ namespace KeePassLib.Cryptography public sealed class CryptoRandom { private byte[] m_pbEntropyPool = new byte[64]; - private uint m_uCounter; + private ulong m_uCounter; private RNGCryptoServiceProvider m_rng = new RNGCryptoServiceProvider(); private ulong m_uGeneratedBytesCount = 0; + private static object g_oSyncRoot = new object(); private object m_oSyncRoot = new object(); - private static CryptoRandom m_pInstance = null; + private static CryptoRandom g_pInstance = null; public static CryptoRandom Instance { get { - if(m_pInstance != null) return m_pInstance; + CryptoRandom cr; + lock(g_oSyncRoot) + { + cr = g_pInstance; + if(cr == null) + { + cr = new CryptoRandom(); + g_pInstance = cr; + } + } - m_pInstance = new CryptoRandom(); - return m_pInstance; + return cr; } } @@ -80,10 +91,12 @@ namespace KeePassLib.Cryptography private CryptoRandom() { - Random r = new Random(); - m_uCounter = (uint)r.Next(); + Random rWeak = new Random(); + byte[] pb = new byte[8]; + rWeak.NextBytes(pb); + m_uCounter = MemUtil.BytesToUInt64(pb); - AddEntropy(GetSystemData(r)); + AddEntropy(GetSystemData(rWeak)); AddEntropy(GetCspData()); } @@ -99,32 +112,40 @@ namespace KeePassLib.Cryptography if(pbEntropy.Length == 0) { Debug.Assert(false); return; } byte[] pbNewData = pbEntropy; - if(pbEntropy.Length >= 64) + if(pbEntropy.Length > 64) { -#if !KeePassLibSD - SHA512Managed shaNew = new SHA512Managed(); +#if KeePassLibSD + using(SHA256Managed shaNew = new SHA256Managed()) #else - SHA256Managed shaNew = new SHA256Managed(); + using(SHA512Managed shaNew = new SHA512Managed()) #endif + { pbNewData = shaNew.ComputeHash(pbEntropy); } + } - MemoryStream ms = new MemoryStream(); lock(m_oSyncRoot) { - ms.Write(m_pbEntropyPool, 0, m_pbEntropyPool.Length); - ms.Write(pbNewData, 0, pbNewData.Length); + int cbPool = m_pbEntropyPool.Length; + int cbNew = pbNewData.Length; - byte[] pbFinal = ms.ToArray(); -#if !KeePassLibSD - Debug.Assert(pbFinal.Length == (64 + pbNewData.Length)); - SHA512Managed shaPool = new SHA512Managed(); + byte[] pbCmp = new byte[cbPool + cbNew]; + Array.Copy(m_pbEntropyPool, pbCmp, cbPool); + Array.Copy(pbNewData, 0, pbCmp, cbPool, cbNew); + + MemUtil.ZeroByteArray(m_pbEntropyPool); + +#if KeePassLibSD + using(SHA256Managed shaPool = new SHA256Managed()) #else - SHA256Managed shaPool = new SHA256Managed(); + using(SHA512Managed shaPool = new SHA512Managed()) #endif - m_pbEntropyPool = shaPool.ComputeHash(pbFinal); + { + m_pbEntropyPool = shaPool.ComputeHash(pbCmp); } - ms.Close(); + + MemUtil.ZeroByteArray(pbCmp); + } } private static byte[] GetSystemData(Random rWeak) @@ -132,71 +153,104 @@ namespace KeePassLib.Cryptography MemoryStream ms = new MemoryStream(); byte[] pb; - pb = MemUtil.UInt32ToBytes((uint)Environment.TickCount); - ms.Write(pb, 0, pb.Length); + pb = MemUtil.Int32ToBytes(Environment.TickCount); + MemUtil.Write(ms, pb); - pb = TimeUtil.PackTime(DateTime.Now); - ms.Write(pb, 0, pb.Length); + pb = MemUtil.Int64ToBytes(DateTime.UtcNow.ToBinary()); + MemUtil.Write(ms, pb); - - pb = MemUtil.UInt32ToBytes((uint)rWeak.Next()); - ms.Write(pb, 0, pb.Length); - - pb = MemUtil.UInt32ToBytes((uint)NativeLib.GetPlatformID()); - ms.Write(pb, 0, pb.Length); - -#if (!KeePassLibSD && !KeePassRT) +#if !KeePassLibSD + /*Not supported on Android + // In try-catch for systems without GUI; + // https://sourceforge.net/p/keepass/discussion/329221/thread/20335b73/ try { - pb = MemUtil.UInt32ToBytes((uint)Environment.ProcessorCount); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)Environment.WorkingSet); - ms.Write(pb, 0, pb.Length); - - Version v = Environment.OSVersion.Version; - int nv = (v.Major << 28) + (v.MajorRevision << 24) + - (v.Minor << 20) + (v.MinorRevision << 16) + - (v.Revision << 12) + v.Build; - pb = MemUtil.UInt32ToBytes((uint)nv); - ms.Write(pb, 0, pb.Length); - - Process p = Process.GetCurrentProcess(); - pb = MemUtil.UInt64ToBytes((ulong)p.Handle.ToInt64()); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt32ToBytes((uint)p.HandleCount); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt32ToBytes((uint)p.Id); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.NonpagedSystemMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PagedMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PagedSystemMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PeakPagedMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PeakVirtualMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PeakWorkingSet64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.PrivateMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.StartTime.ToBinary()); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.VirtualMemorySize64); - ms.Write(pb, 0, pb.Length); - pb = MemUtil.UInt64ToBytes((ulong)p.WorkingSet64); - ms.Write(pb, 0, pb.Length); - - // Not supported in Mono 1.2.6: - // pb = MemUtil.UInt32ToBytes((uint)p.SessionId); - // ms.Write(pb, 0, pb.Length); + Point pt = Cursor.Position; + pb = MemUtil.Int32ToBytes(pt.X); + MemUtil.Write(ms, pb); + pb = MemUtil.Int32ToBytes(pt.Y); + MemUtil.Write(ms, pb); } catch(Exception) { } + */ +#endif + + pb = MemUtil.Int32ToBytes(rWeak.Next()); + MemUtil.Write(ms, pb); + + pb = MemUtil.UInt32ToBytes((uint)NativeLib.GetPlatformID()); + MemUtil.Write(ms, pb); + + try + { + pb = MemUtil.Int32ToBytes(Environment.ProcessorCount); + MemUtil.Write(ms, pb); + +#if KeePassUAP + Version v = EnvironmentExt.OSVersion.Version; +#else + Version v = Environment.OSVersion.Version; +#endif + pb = MemUtil.Int32ToBytes(v.GetHashCode()); + MemUtil.Write(ms, pb); + +#if !KeePassUAP + pb = MemUtil.Int64ToBytes(Environment.WorkingSet); + MemUtil.Write(ms, pb); +#endif + } + catch(Exception) { Debug.Assert(false); } + +#if KeePassUAP + pb = DiagnosticsExt.GetProcessEntropy(); + MemUtil.Write(ms, pb); +#elif !KeePassLibSD + Process p = null; + try + { + p = Process.GetCurrentProcess(); + // Not supported in Mono 1.2.6: + pb = MemUtil.Int64ToBytes(p.Handle.ToInt64()); + MemUtil.Write(ms, pb); + pb = MemUtil.Int32ToBytes(p.HandleCount); + MemUtil.Write(ms, pb); + pb = MemUtil.Int32ToBytes(p.Id); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.NonpagedSystemMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PagedMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PagedSystemMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PeakPagedMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PeakVirtualMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PeakWorkingSet64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.PrivateMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.StartTime.ToBinary()); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.VirtualMemorySize64); + MemUtil.Write(ms, pb); + pb = MemUtil.Int64ToBytes(p.WorkingSet64); + MemUtil.Write(ms, pb); + // pb = MemUtil.UInt32ToBytes((uint)p.SessionId); + // ms.Write(pb, 0, pb.Length); + // pb = MemUtil.UInt32ToBytes((uint)p.SessionId); + // MemUtil.Write(ms, pb); + } + catch(Exception) { Debug.Assert(NativeLib.IsUnix()); } + finally + { + try { if(p != null) p.Dispose(); } + catch(Exception) { Debug.Assert(false); } + } #endif pb = Guid.NewGuid().ToByteArray(); - ms.Write(pb, 0, pb.Length); + MemUtil.Write(ms, pb); byte[] pbAll = ms.ToArray(); ms.Close(); @@ -215,28 +269,31 @@ namespace KeePassLib.Cryptography if(this.GenerateRandom256Pre != null) this.GenerateRandom256Pre(this, EventArgs.Empty); - byte[] pbFinal; + byte[] pbCmp; lock(m_oSyncRoot) { - unchecked { m_uCounter += 386047; } // Prime number - byte[] pbCounter = MemUtil.UInt32ToBytes(m_uCounter); + m_uCounter += 0x74D8B29E4D38E161UL; // Prime number + byte[] pbCounter = MemUtil.UInt64ToBytes(m_uCounter); byte[] pbCspRandom = GetCspData(); - MemoryStream ms = new MemoryStream(); - ms.Write(m_pbEntropyPool, 0, m_pbEntropyPool.Length); - ms.Write(pbCounter, 0, pbCounter.Length); - ms.Write(pbCspRandom, 0, pbCspRandom.Length); - pbFinal = ms.ToArray(); - Debug.Assert(pbFinal.Length == (m_pbEntropyPool.Length + - pbCounter.Length + pbCspRandom.Length)); - ms.Close(); + int cbPool = m_pbEntropyPool.Length; + int cbCtr = pbCounter.Length; + int cbCsp = pbCspRandom.Length; + + pbCmp = new byte[cbPool + cbCtr + cbCsp]; + Array.Copy(m_pbEntropyPool, pbCmp, cbPool); + Array.Copy(pbCounter, 0, pbCmp, cbPool, cbCtr); + Array.Copy(pbCspRandom, 0, pbCmp, cbPool + cbCtr, cbCsp); + + MemUtil.ZeroByteArray(pbCspRandom); m_uGeneratedBytesCount += 32; } - SHA256Managed sha256 = new SHA256Managed(); - return sha256.ComputeHash(pbFinal); + byte[] pbRet = CryptoUtil.HashSha256(pbCmp); + MemUtil.ZeroByteArray(pbCmp); + return pbRet; } /// @@ -248,29 +305,32 @@ namespace KeePassLib.Cryptography /// random bytes. public byte[] GetRandomBytes(uint uRequestedBytes) { - if(uRequestedBytes == 0) return new byte[0]; // Allow zero-length array + if(uRequestedBytes == 0) return MemUtil.EmptyByteArray; + if(uRequestedBytes > (uint)int.MaxValue) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("uRequestedBytes"); + } - byte[] pbRes = new byte[uRequestedBytes]; - long lPos = 0; + int cbRem = (int)uRequestedBytes; + byte[] pbRes = new byte[cbRem]; + int iPos = 0; - while(uRequestedBytes != 0) + while(cbRem != 0) { byte[] pbRandom256 = GenerateRandom256(); Debug.Assert(pbRandom256.Length == 32); - long lCopy = (long)((uRequestedBytes < 32) ? uRequestedBytes : 32); + int cbCopy = Math.Min(cbRem, 32); + Array.Copy(pbRandom256, 0, pbRes, iPos, cbCopy); -#if (!KeePassLibSD && !KeePassRT) - Array.Copy(pbRandom256, 0, pbRes, lPos, lCopy); -#else - Array.Copy(pbRandom256, 0, pbRes, (int)lPos, (int)lCopy); -#endif + MemUtil.ZeroByteArray(pbRandom256); - lPos += lCopy; - uRequestedBytes -= (uint)lCopy; + iPos += cbCopy; + cbRem -= cbCopy; } - Debug.Assert((int)lPos == pbRes.Length); + Debug.Assert(iPos == pbRes.Length); return pbRes; } } diff --git a/src/KeePassLib2Android/Cryptography/CryptoRandomStream.cs b/src/KeePassLib2Android/Cryptography/CryptoRandomStream.cs index 07ce15dd..37367f0b 100644 --- a/src/KeePassLib2Android/Cryptography/CryptoRandomStream.cs +++ b/src/KeePassLib2Android/Cryptography/CryptoRandomStream.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,9 +19,13 @@ using System; using System.Diagnostics; + +#if !KeePassUAP using System.Security.Cryptography; +#endif using KeePassLib.Cryptography.Cipher; +using KeePassLib.Utility; namespace KeePassLib.Cryptography { @@ -38,6 +42,7 @@ namespace KeePassLib.Cryptography /// /// A variant of the ARCFour algorithm (RC4 incompatible). /// + /// ArcFourVariant = 1, /// @@ -45,7 +50,12 @@ namespace KeePassLib.Cryptography /// Salsa20 = 2, - Count = 3 + /// + /// ChaCha20 stream cipher algorithm. + /// + ChaCha20 = 3, + + Count = 4 } /// @@ -56,13 +66,14 @@ namespace KeePassLib.Cryptography /// public sealed class CryptoRandomStream { - private CrsAlgorithm m_crsAlgorithm; + private readonly CrsAlgorithm m_crsAlgorithm; private byte[] m_pbState = null; private byte m_i = 0; private byte m_j = 0; private Salsa20Cipher m_salsa20 = null; + private ChaCha20Cipher m_chacha20 = null; /// /// Construct a new cryptographically secure random stream object. @@ -70,31 +81,53 @@ namespace KeePassLib.Cryptography /// Algorithm to use. /// Initialization key. Must not be null and /// must contain at least 1 byte. - /// Thrown if the - /// parameter is null. - /// Thrown if the - /// parameter contains no bytes or the - /// algorithm is unknown. - public CryptoRandomStream(CrsAlgorithm genAlgorithm, byte[] pbKey) + public CryptoRandomStream(CrsAlgorithm a, byte[] pbKey) { - m_crsAlgorithm = genAlgorithm; + if(pbKey == null) { Debug.Assert(false); throw new ArgumentNullException("pbKey"); } + /// Thrown if the + int cbKey = pbKey.Length; + if(cbKey <= 0) + { + Debug.Assert(false); // Need at least one byte + throw new ArgumentOutOfRangeException("pbKey"); + } + /// parameter is null. + m_crsAlgorithm = a; + /// Thrown if the + if(a == CrsAlgorithm.ChaCha20) + { + byte[] pbKey32 = new byte[32]; + byte[] pbIV12 = new byte[12]; + /// parameter contains no bytes or the + using(SHA512Managed h = new SHA512Managed()) + { + byte[] pbHash = h.ComputeHash(pbKey); + Array.Copy(pbHash, pbKey32, 32); + Array.Copy(pbHash, 32, pbIV12, 0, 12); + MemUtil.ZeroByteArray(pbHash); + } + /// algorithm is unknown. + m_chacha20 = new ChaCha20Cipher(pbKey32, pbIV12, true); + } + else if(a == CrsAlgorithm.Salsa20) + { + byte[] pbKey32 = CryptoUtil.HashSha256(pbKey); + byte[] pbIV8 = new byte[8] { 0xE8, 0x30, 0x09, 0x4B, + 0x97, 0x20, 0x5D, 0x2A }; // Unique constant - Debug.Assert(pbKey != null); if(pbKey == null) throw new ArgumentNullException("pbKey"); - - uint uKeyLen = (uint)pbKey.Length; - Debug.Assert(uKeyLen != 0); if(uKeyLen == 0) throw new ArgumentException(); - - if(genAlgorithm == CrsAlgorithm.ArcFourVariant) + m_salsa20 = new Salsa20Cipher(pbKey32, pbIV8); + } + else if(a == CrsAlgorithm.ArcFourVariant) { // Fill the state linearly m_pbState = new byte[256]; - for(uint w = 0; w < 256; ++w) m_pbState[w] = (byte)w; + for(int w = 0; w < 256; ++w) m_pbState[w] = (byte)w; unchecked { byte j = 0, t; - uint inxKey = 0; - for(uint w = 0; w < 256; ++w) // Key setup + int inxKey = 0; + for(int w = 0; w < 256; ++w) // Key setup { j += (byte)(m_pbState[w] + pbKey[inxKey]); @@ -103,25 +136,16 @@ namespace KeePassLib.Cryptography m_pbState[j] = t; ++inxKey; - if(inxKey >= uKeyLen) inxKey = 0; + if(inxKey >= cbKey) inxKey = 0; } } GetRandomBytes(512); // Increases security, see cryptanalysis } - else if(genAlgorithm == CrsAlgorithm.Salsa20) - { - SHA256Managed sha256 = new SHA256Managed(); - byte[] pbKey32 = sha256.ComputeHash(pbKey); - byte[] pbIV = new byte[]{ 0xE8, 0x30, 0x09, 0x4B, - 0x97, 0x20, 0x5D, 0x2A }; // Unique constant - - m_salsa20 = new Salsa20Cipher(pbKey32, pbIV); - } else // Unknown algorithm { Debug.Assert(false); - throw new ArgumentException(); + throw new ArgumentOutOfRangeException("a"); } } @@ -132,15 +156,23 @@ namespace KeePassLib.Cryptography /// Returns random bytes. public byte[] GetRandomBytes(uint uRequestedCount) { - if(uRequestedCount == 0) return new byte[0]; + if(uRequestedCount == 0) return MemUtil.EmptyByteArray; - byte[] pbRet = new byte[uRequestedCount]; + if(uRequestedCount > (uint)int.MaxValue) + throw new ArgumentOutOfRangeException("uRequestedCount"); + int cb = (int)uRequestedCount; - if(m_crsAlgorithm == CrsAlgorithm.ArcFourVariant) + byte[] pbRet = new byte[cb]; + + if(m_crsAlgorithm == CrsAlgorithm.ChaCha20) + m_chacha20.Encrypt(pbRet, 0, cb); + else if(m_crsAlgorithm == CrsAlgorithm.Salsa20) + m_salsa20.Encrypt(pbRet, 0, cb); + else if(m_crsAlgorithm == CrsAlgorithm.ArcFourVariant) { unchecked { - for(uint w = 0; w < uRequestedCount; ++w) + for(int w = 0; w < cb; ++w) { ++m_i; m_j += m_pbState[m_i]; @@ -154,8 +186,6 @@ namespace KeePassLib.Cryptography } } } - else if(m_crsAlgorithm == CrsAlgorithm.Salsa20) - m_salsa20.Encrypt(pbRet, pbRet.Length, false); else { Debug.Assert(false); } return pbRet; @@ -164,15 +194,8 @@ namespace KeePassLib.Cryptography public ulong GetRandomUInt64() { byte[] pb = GetRandomBytes(8); - - unchecked - { - return ((ulong)pb[0]) | ((ulong)pb[1] << 8) | - ((ulong)pb[2] << 16) | ((ulong)pb[3] << 24) | - ((ulong)pb[4] << 32) | ((ulong)pb[5] << 40) | - ((ulong)pb[6] << 48) | ((ulong)pb[7] << 56); + return MemUtil.BytesToUInt64(pb); } - } #if CRSBENCHMARK public static string Benchmark() diff --git a/src/KeePassLib2Android/Cryptography/CryptoUtil.cs b/src/KeePassLib2Android/Cryptography/CryptoUtil.cs new file mode 100644 index 00000000..9cb7bcd6 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/CryptoUtil.cs @@ -0,0 +1,126 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; + +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography +{ + public static class CryptoUtil + { + public static byte[] HashSha256(byte[] pbData) + { + if(pbData == null) throw new ArgumentNullException("pbData"); + + return HashSha256(pbData, 0, pbData.Length); + } + + public static byte[] HashSha256(byte[] pbData, int iOffset, int cbCount) + { + if(pbData == null) throw new ArgumentNullException("pbData"); + +#if DEBUG + byte[] pbCopy = new byte[pbData.Length]; + Array.Copy(pbData, pbCopy, pbData.Length); +#endif + + byte[] pbHash; + using(SHA256Managed h = new SHA256Managed()) + { + pbHash = h.ComputeHash(pbData, iOffset, cbCount); + } + +#if DEBUG + // Ensure the data has not been modified + Debug.Assert(MemUtil.ArraysEqual(pbData, pbCopy)); + + Debug.Assert((pbHash != null) && (pbHash.Length == 32)); + byte[] pbZero = new byte[32]; + Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero)); +#endif + + return pbHash; + } + + /// + /// Create a cryptographic key of length + /// (in bytes) from . + /// + public static byte[] ResizeKey(byte[] pbIn, int iInOffset, + int cbIn, int cbOut) + { + if(pbIn == null) throw new ArgumentNullException("pbIn"); + if(cbOut < 0) throw new ArgumentOutOfRangeException("cbOut"); + + if(cbOut == 0) return MemUtil.EmptyByteArray; + + byte[] pbHash; + if(cbOut <= 32) pbHash = HashSha256(pbIn, iInOffset, cbIn); + else + { + using(SHA512Managed h = new SHA512Managed()) + { + pbHash = h.ComputeHash(pbIn, iInOffset, cbIn); + } + } + + if(cbOut == pbHash.Length) return pbHash; + + byte[] pbRet = new byte[cbOut]; + if(cbOut < pbHash.Length) + Array.Copy(pbHash, pbRet, cbOut); + else + { + int iPos = 0; + ulong r = 0; + while(iPos < cbOut) + { + Debug.Assert(pbHash.Length == 64); + using(HMACSHA256 h = new HMACSHA256(pbHash)) + { + byte[] pbR = MemUtil.UInt64ToBytes(r); + byte[] pbPart = h.ComputeHash(pbR); + + int cbCopy = Math.Min(cbOut - iPos, pbPart.Length); + Debug.Assert(cbCopy > 0); + + Array.Copy(pbPart, 0, pbRet, iPos, cbCopy); + iPos += cbCopy; + ++r; + + MemUtil.ZeroByteArray(pbPart); + } + } + Debug.Assert(iPos == cbOut); + } + +#if DEBUG + byte[] pbZero = new byte[pbHash.Length]; + Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero)); +#endif + MemUtil.ZeroByteArray(pbHash); + return pbRet; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/Hash/Blake2b.cs b/src/KeePassLib2Android/Cryptography/Hash/Blake2b.cs new file mode 100644 index 00000000..1a446aaa --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/Hash/Blake2b.cs @@ -0,0 +1,229 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +// This implementation is based on the official reference C +// implementation by Samuel Neves (CC0 1.0 Universal). + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; + +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.Hash +{ + public sealed class Blake2b : HashAlgorithm + { + private const int NbRounds = 12; + private const int NbBlockBytes = 128; + private const int NbMaxOutBytes = 64; + + private static readonly ulong[] g_vIV = new ulong[8] { + 0x6A09E667F3BCC908UL, 0xBB67AE8584CAA73BUL, + 0x3C6EF372FE94F82BUL, 0xA54FF53A5F1D36F1UL, + 0x510E527FADE682D1UL, 0x9B05688C2B3E6C1FUL, + 0x1F83D9ABFB41BD6BUL, 0x5BE0CD19137E2179UL + }; + + private static readonly int[] g_vSigma = new int[NbRounds * 16] { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 + }; + + private readonly int m_cbHashLength; + + private ulong[] m_h = new ulong[8]; + private ulong[] m_t = new ulong[2]; + private ulong[] m_f = new ulong[2]; + private byte[] m_buf = new byte[NbBlockBytes]; + private int m_cbBuf = 0; + + private ulong[] m_m = new ulong[16]; + private ulong[] m_v = new ulong[16]; + + public Blake2b() + { + m_cbHashLength = NbMaxOutBytes; + this.HashSizeValue = NbMaxOutBytes * 8; // Bits + + Initialize(); + } + + public Blake2b(int cbHashLength) + { + if((cbHashLength < 0) || (cbHashLength > NbMaxOutBytes)) + throw new ArgumentOutOfRangeException("cbHashLength"); + + m_cbHashLength = cbHashLength; + this.HashSizeValue = cbHashLength * 8; // Bits + + Initialize(); + } + + public override void Initialize() + { + Debug.Assert(m_h.Length == g_vIV.Length); + Array.Copy(g_vIV, m_h, m_h.Length); + + // Fan-out = 1, depth = 1 + m_h[0] ^= 0x0000000001010000UL ^ (ulong)m_cbHashLength; + + Array.Clear(m_t, 0, m_t.Length); + Array.Clear(m_f, 0, m_f.Length); + Array.Clear(m_buf, 0, m_buf.Length); + m_cbBuf = 0; + + Array.Clear(m_m, 0, m_m.Length); + Array.Clear(m_v, 0, m_v.Length); + } + + private static void G(ulong[] v, ulong[] m, int r16, int i, + int a, int b, int c, int d) + { + int p = r16 + i; + + v[a] += v[b] + m[g_vSigma[p]]; + v[d] = MemUtil.RotateRight64(v[d] ^ v[a], 32); + v[c] += v[d]; + v[b] = MemUtil.RotateRight64(v[b] ^ v[c], 24); + v[a] += v[b] + m[g_vSigma[p + 1]]; + v[d] = MemUtil.RotateRight64(v[d] ^ v[a], 16); + v[c] += v[d]; + v[b] = MemUtil.RotateRight64(v[b] ^ v[c], 63); + } + + private void Compress(byte[] pb, int iOffset) + { + ulong[] v = m_v; + ulong[] m = m_m; + ulong[] h = m_h; + + for(int i = 0; i < 16; ++i) + m[i] = MemUtil.BytesToUInt64(pb, iOffset + (i << 3)); + + Array.Copy(h, v, 8); + v[8] = g_vIV[0]; + v[9] = g_vIV[1]; + v[10] = g_vIV[2]; + v[11] = g_vIV[3]; + v[12] = g_vIV[4] ^ m_t[0]; + v[13] = g_vIV[5] ^ m_t[1]; + v[14] = g_vIV[6] ^ m_f[0]; + v[15] = g_vIV[7] ^ m_f[1]; + + for(int r = 0; r < NbRounds; ++r) + { + int r16 = r << 4; + + G(v, m, r16, 0, 0, 4, 8, 12); + G(v, m, r16, 2, 1, 5, 9, 13); + G(v, m, r16, 4, 2, 6, 10, 14); + G(v, m, r16, 6, 3, 7, 11, 15); + G(v, m, r16, 8, 0, 5, 10, 15); + G(v, m, r16, 10, 1, 6, 11, 12); + G(v, m, r16, 12, 2, 7, 8, 13); + G(v, m, r16, 14, 3, 4, 9, 14); + } + + for(int i = 0; i < 8; ++i) + h[i] ^= v[i] ^ v[i + 8]; + } + + private void IncrementCounter(ulong cb) + { + m_t[0] += cb; + if(m_t[0] < cb) ++m_t[1]; + } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + Debug.Assert(m_f[0] == 0); + + if((m_cbBuf + cbSize) > NbBlockBytes) // Not '>=' (buffer must not be empty) + { + int cbFill = NbBlockBytes - m_cbBuf; + if(cbFill > 0) Array.Copy(array, ibStart, m_buf, m_cbBuf, cbFill); + + IncrementCounter((ulong)NbBlockBytes); + Compress(m_buf, 0); + + m_cbBuf = 0; + cbSize -= cbFill; + ibStart += cbFill; + + while(cbSize > NbBlockBytes) // Not '>=' (buffer must not be empty) + { + IncrementCounter((ulong)NbBlockBytes); + Compress(array, ibStart); + + cbSize -= NbBlockBytes; + ibStart += NbBlockBytes; + } + } + + if(cbSize > 0) + { + Debug.Assert((m_cbBuf + cbSize) <= NbBlockBytes); + + Array.Copy(array, ibStart, m_buf, m_cbBuf, cbSize); + m_cbBuf += cbSize; + } + } + + protected override byte[] HashFinal() + { + if(m_f[0] != 0) { Debug.Assert(false); throw new InvalidOperationException(); } + Debug.Assert(((m_t[1] == 0) && (m_t[0] == 0)) || + (m_cbBuf > 0)); // Buffer must not be empty for last block processing + + m_f[0] = ulong.MaxValue; // Indicate last block + + int cbFill = NbBlockBytes - m_cbBuf; + if(cbFill > 0) Array.Clear(m_buf, m_cbBuf, cbFill); + + IncrementCounter((ulong)m_cbBuf); + Compress(m_buf, 0); + + byte[] pbHash = new byte[NbMaxOutBytes]; + for(int i = 0; i < m_h.Length; ++i) + MemUtil.UInt64ToBytesEx(m_h[i], pbHash, i << 3); + + if(m_cbHashLength == NbMaxOutBytes) return pbHash; + Debug.Assert(m_cbHashLength < NbMaxOutBytes); + + byte[] pbShort = new byte[m_cbHashLength]; + if(m_cbHashLength > 0) + Array.Copy(pbHash, pbShort, m_cbHashLength); + MemUtil.ZeroByteArray(pbHash); + return pbShort; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/AesKdf.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/AesKdf.cs new file mode 100644 index 00000000..fcc7cda6 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/AesKdf.cs @@ -0,0 +1,270 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +#if KeePassUAP +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Parameters; +#else +using System.Security.Cryptography; +#endif + +using KeePassLib.Cryptography; +using KeePassLib.Native; +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public sealed class AesKdf : KdfEngine + { + private static readonly PwUuid g_uuid = new PwUuid(new byte[] { + 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, + 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA }); + + public const string ParamRounds = "R"; // UInt64 + public const string ParamSeed = "S"; // Byte[32] + + public override PwUuid Uuid + { + get { return g_uuid; } + } + + public override string Name + { + get { return "AES-KDF"; } + } + + public AesKdf() + { + } + + public override KdfParameters GetDefaultParameters() + { + KdfParameters p = base.GetDefaultParameters(); + p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds); + return p; + } + + public override void Randomize(KdfParameters p) + { + if(p == null) { Debug.Assert(false); return; } + Debug.Assert(g_uuid.Equals(p.KdfUuid)); + + byte[] pbSeed = CryptoRandom.Instance.GetRandomBytes(32); + p.SetByteArray(ParamSeed, pbSeed); + } + + public override byte[] Transform(byte[] pbMsg, KdfParameters p) + { + if(pbMsg == null) throw new ArgumentNullException("pbMsg"); + if(p == null) throw new ArgumentNullException("p"); + + Type tRounds = p.GetTypeOf(ParamRounds); + if(tRounds == null) throw new ArgumentNullException("p.Rounds"); + if(tRounds != typeof(ulong)) throw new ArgumentOutOfRangeException("p.Rounds"); + ulong uRounds = p.GetUInt64(ParamRounds, 0); + + byte[] pbSeed = p.GetByteArray(ParamSeed); + if(pbSeed == null) throw new ArgumentNullException("p.Seed"); + + if(pbMsg.Length != 32) + { + Debug.Assert(false); + pbMsg = CryptoUtil.HashSha256(pbMsg); + } + + if(pbSeed.Length != 32) + { + Debug.Assert(false); + pbSeed = CryptoUtil.HashSha256(pbSeed); + } + + return TransformKey(pbMsg, pbSeed, uRounds); + } + + private static byte[] TransformKey(byte[] pbOriginalKey32, byte[] pbKeySeed32, + ulong uNumRounds) + { + Debug.Assert((pbOriginalKey32 != null) && (pbOriginalKey32.Length == 32)); + if(pbOriginalKey32 == null) throw new ArgumentNullException("pbOriginalKey32"); + if(pbOriginalKey32.Length != 32) throw new ArgumentException(); + + Debug.Assert((pbKeySeed32 != null) && (pbKeySeed32.Length == 32)); + if(pbKeySeed32 == null) throw new ArgumentNullException("pbKeySeed32"); + if(pbKeySeed32.Length != 32) throw new ArgumentException(); + + byte[] pbNewKey = new byte[32]; + Array.Copy(pbOriginalKey32, pbNewKey, pbNewKey.Length); + + try + { + // Try to use the native library first + if(NativeLib.TransformKey256(pbNewKey, pbKeySeed32, uNumRounds)) + return CryptoUtil.HashSha256(pbNewKey); + + if(TransformKeyManaged(pbNewKey, pbKeySeed32, uNumRounds)) + return CryptoUtil.HashSha256(pbNewKey); + } + finally { MemUtil.ZeroByteArray(pbNewKey); } + + return null; + } + + public static bool TransformKeyManaged(byte[] pbNewKey32, byte[] pbKeySeed32, + ulong uNumRounds) + { +#if KeePassUAP + KeyParameter kp = new KeyParameter(pbKeySeed32); + AesEngine aes = new AesEngine(); + aes.Init(true, kp); + + for(ulong i = 0; i < uNumRounds; ++i) + { + aes.ProcessBlock(pbNewKey32, 0, pbNewKey32, 0); + aes.ProcessBlock(pbNewKey32, 16, pbNewKey32, 16); + } +#else + byte[] pbIV = new byte[16]; + Array.Clear(pbIV, 0, pbIV.Length); + + RijndaelManaged r = new RijndaelManaged(); + if(r.BlockSize != 128) // AES block size + { + Debug.Assert(false); + r.BlockSize = 128; + } + + r.IV = pbIV; + r.Mode = CipherMode.ECB; + r.KeySize = 256; + r.Key = pbKeySeed32; + ICryptoTransform iCrypt = r.CreateEncryptor(); + + // !iCrypt.CanReuseTransform -- doesn't work with Mono + if((iCrypt == null) || (iCrypt.InputBlockSize != 16) || + (iCrypt.OutputBlockSize != 16)) + { + Debug.Assert(false, "Invalid ICryptoTransform."); + Debug.Assert((iCrypt.InputBlockSize == 16), "Invalid input block size!"); + Debug.Assert((iCrypt.OutputBlockSize == 16), "Invalid output block size!"); + return false; + } + + for(ulong i = 0; i < uNumRounds; ++i) + { + iCrypt.TransformBlock(pbNewKey32, 0, 16, pbNewKey32, 0); + iCrypt.TransformBlock(pbNewKey32, 16, 16, pbNewKey32, 16); + } +#endif + + return true; + } + + public override KdfParameters GetBestParameters(uint uMilliseconds) + { + const ulong uStep = 3001; + ulong uRounds; + + KdfParameters p = GetDefaultParameters(); + + // Try native method + if(NativeLib.TransformKeyBenchmark256(uMilliseconds, out uRounds)) + { + p.SetUInt64(ParamRounds, uRounds); + return p; + } + + byte[] pbKey = new byte[32]; + byte[] pbNewKey = new byte[32]; + for(int i = 0; i < pbKey.Length; ++i) + { + pbKey[i] = (byte)i; + pbNewKey[i] = (byte)i; + } + +#if KeePassUAP + KeyParameter kp = new KeyParameter(pbKey); + AesEngine aes = new AesEngine(); + aes.Init(true, kp); +#else + byte[] pbIV = new byte[16]; + Array.Clear(pbIV, 0, pbIV.Length); + + RijndaelManaged r = new RijndaelManaged(); + if(r.BlockSize != 128) // AES block size + { + Debug.Assert(false); + r.BlockSize = 128; + } + + r.IV = pbIV; + r.Mode = CipherMode.ECB; + r.KeySize = 256; + r.Key = pbKey; + ICryptoTransform iCrypt = r.CreateEncryptor(); + + // !iCrypt.CanReuseTransform -- doesn't work with Mono + if((iCrypt == null) || (iCrypt.InputBlockSize != 16) || + (iCrypt.OutputBlockSize != 16)) + { + Debug.Assert(false, "Invalid ICryptoTransform."); + Debug.Assert(iCrypt.InputBlockSize == 16, "Invalid input block size!"); + Debug.Assert(iCrypt.OutputBlockSize == 16, "Invalid output block size!"); + + p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds); + return p; + } +#endif + + uRounds = 0; + int tStart = Environment.TickCount; + while(true) + { + for(ulong j = 0; j < uStep; ++j) + { +#if KeePassUAP + aes.ProcessBlock(pbNewKey, 0, pbNewKey, 0); + aes.ProcessBlock(pbNewKey, 16, pbNewKey, 16); +#else + iCrypt.TransformBlock(pbNewKey, 0, 16, pbNewKey, 0); + iCrypt.TransformBlock(pbNewKey, 16, 16, pbNewKey, 16); +#endif + } + + uRounds += uStep; + if(uRounds < uStep) // Overflow check + { + uRounds = ulong.MaxValue; + break; + } + + uint tElapsed = (uint)(Environment.TickCount - tStart); + if(tElapsed > uMilliseconds) break; + } + + p.SetUInt64(ParamRounds, uRounds); + return p; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.Core.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.Core.cs new file mode 100644 index 00000000..bd90c427 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.Core.cs @@ -0,0 +1,610 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +// This implementation is based on the official reference C +// implementation by Daniel Dinu and Dmitry Khovratovich (CC0 1.0). + +// Relative iterations (* = B2ROUND_ARRAYS \\ G_INLINED): +// * | false true +// ------+----------- +// false | 8885 9618 +// true | 9009 9636 +#define ARGON2_B2ROUND_ARRAYS +#define ARGON2_G_INLINED + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +using KeePassLib.Cryptography.Hash; +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public sealed partial class Argon2Kdf : KdfEngine + { + private const ulong NbBlockSize = 1024; + private const ulong NbBlockSizeInQW = NbBlockSize / 8UL; + private const ulong NbSyncPoints = 4; + + private const int NbPreHashDigestLength = 64; + private const int NbPreHashSeedLength = NbPreHashDigestLength + 8; + +#if ARGON2_B2ROUND_ARRAYS + private static int[][] g_vFBCols = null; + private static int[][] g_vFBRows = null; +#endif + + private sealed class Argon2Ctx + { + public uint Version = 0; + + public ulong Lanes = 0; + public ulong TCost = 0; + public ulong MCost = 0; + public ulong MemoryBlocks = 0; + public ulong SegmentLength = 0; + public ulong LaneLength = 0; + + public ulong[] Mem = null; + } + + private sealed class Argon2ThreadInfo + { + public Argon2Ctx Context = null; + public ManualResetEvent Finished = new ManualResetEvent(false); + + public ulong Pass = 0; + public ulong Lane = 0; + public ulong Slice = 0; + public ulong Index = 0; + } + + private static byte[] Argon2d(byte[] pbMsg, byte[] pbSalt, uint uParallel, + ulong uMem, ulong uIt, int cbOut, uint uVersion, byte[] pbSecretKey, + byte[] pbAssocData) + { + pbSecretKey = (pbSecretKey ?? MemUtil.EmptyByteArray); + pbAssocData = (pbAssocData ?? MemUtil.EmptyByteArray); + +#if ARGON2_B2ROUND_ARRAYS + InitB2RoundIndexArrays(); +#endif + + Argon2Ctx ctx = new Argon2Ctx(); + ctx.Version = uVersion; + + ctx.Lanes = uParallel; + ctx.TCost = uIt; + ctx.MCost = uMem / NbBlockSize; + ctx.MemoryBlocks = Math.Max(ctx.MCost, 2UL * NbSyncPoints * ctx.Lanes); + + ctx.SegmentLength = ctx.MemoryBlocks / (ctx.Lanes * NbSyncPoints); + ctx.MemoryBlocks = ctx.SegmentLength * ctx.Lanes * NbSyncPoints; + + ctx.LaneLength = ctx.SegmentLength * NbSyncPoints; + + Debug.Assert(NbBlockSize == (NbBlockSizeInQW * + (ulong)Marshal.SizeOf(typeof(ulong)))); + ctx.Mem = new ulong[ctx.MemoryBlocks * NbBlockSizeInQW]; + + Blake2b h = new Blake2b(); + + // Initial hash + Debug.Assert(h.HashSize == (NbPreHashDigestLength * 8)); + byte[] pbBuf = new byte[4]; + MemUtil.UInt32ToBytesEx(uParallel, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx((uint)cbOut, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx((uint)ctx.MCost, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx((uint)uIt, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx(uVersion, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx(0, pbBuf, 0); // Argon2d type = 0 + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + MemUtil.UInt32ToBytesEx((uint)pbMsg.Length, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0); + MemUtil.UInt32ToBytesEx((uint)pbSalt.Length, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + h.TransformBlock(pbSalt, 0, pbSalt.Length, pbSalt, 0); + MemUtil.UInt32ToBytesEx((uint)pbSecretKey.Length, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + h.TransformBlock(pbSecretKey, 0, pbSecretKey.Length, pbSecretKey, 0); + MemUtil.UInt32ToBytesEx((uint)pbAssocData.Length, pbBuf, 0); + h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0); + h.TransformBlock(pbAssocData, 0, pbAssocData.Length, pbAssocData, 0); + h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + byte[] pbH0 = h.Hash; + Debug.Assert(pbH0.Length == 64); + + byte[] pbBlockHash = new byte[NbPreHashSeedLength]; + Array.Copy(pbH0, pbBlockHash, pbH0.Length); + MemUtil.ZeroByteArray(pbH0); + + FillFirstBlocks(ctx, pbBlockHash, h); + MemUtil.ZeroByteArray(pbBlockHash); + + FillMemoryBlocks(ctx); + + byte[] pbOut = FinalHash(ctx, cbOut, h); + + h.Clear(); + MemUtil.ZeroArray(ctx.Mem); + return pbOut; + } + + private static void LoadBlock(ulong[] pqDst, ulong uDstOffset, byte[] pbIn) + { + // for(ulong i = 0; i < NbBlockSizeInQW; ++i) + // pqDst[uDstOffset + i] = MemUtil.BytesToUInt64(pbIn, (int)(i << 3)); + + Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue); + int iDstOffset = (int)uDstOffset; + for(int i = 0; i < (int)NbBlockSizeInQW; ++i) + pqDst[iDstOffset + i] = MemUtil.BytesToUInt64(pbIn, i << 3); + } + + private static void StoreBlock(byte[] pbDst, ulong[] pqSrc) + { + for(int i = 0; i < (int)NbBlockSizeInQW; ++i) + MemUtil.UInt64ToBytesEx(pqSrc[i], pbDst, i << 3); + } + + private static void CopyBlock(ulong[] vDst, ulong uDstOffset, ulong[] vSrc, + ulong uSrcOffset) + { + // for(ulong i = 0; i < NbBlockSizeInQW; ++i) + // vDst[uDstOffset + i] = vSrc[uSrcOffset + i]; + + // Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue); + // Debug.Assert((uSrcOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue); + // int iDstOffset = (int)uDstOffset; + // int iSrcOffset = (int)uSrcOffset; + // for(int i = 0; i < (int)NbBlockSizeInQW; ++i) + // vDst[iDstOffset + i] = vSrc[iSrcOffset + i]; + + Array.Copy(vSrc, (long)uSrcOffset, vDst, (long)uDstOffset, + (long)NbBlockSizeInQW); + } + + private static void XorBlock(ulong[] vDst, ulong uDstOffset, ulong[] vSrc, + ulong uSrcOffset) + { + // for(ulong i = 0; i < NbBlockSizeInQW; ++i) + // vDst[uDstOffset + i] ^= vSrc[uSrcOffset + i]; + + Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue); + Debug.Assert((uSrcOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue); + int iDstOffset = (int)uDstOffset; + int iSrcOffset = (int)uSrcOffset; + for(int i = 0; i < (int)NbBlockSizeInQW; ++i) + vDst[iDstOffset + i] ^= vSrc[iSrcOffset + i]; + } + + private static void Blake2bLong(byte[] pbOut, int cbOut, + byte[] pbIn, int cbIn, Blake2b h) + { + Debug.Assert((h != null) && (h.HashSize == (64 * 8))); + + byte[] pbOutLen = new byte[4]; + MemUtil.UInt32ToBytesEx((uint)cbOut, pbOutLen, 0); + + if(cbOut <= 64) + { + Blake2b hOut = ((cbOut == 64) ? h : new Blake2b(cbOut)); + if(cbOut == 64) hOut.Initialize(); + + hOut.TransformBlock(pbOutLen, 0, pbOutLen.Length, pbOutLen, 0); + hOut.TransformBlock(pbIn, 0, cbIn, pbIn, 0); + hOut.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + + Array.Copy(hOut.Hash, pbOut, cbOut); + + if(cbOut < 64) hOut.Clear(); + return; + } + + h.Initialize(); + h.TransformBlock(pbOutLen, 0, pbOutLen.Length, pbOutLen, 0); + h.TransformBlock(pbIn, 0, cbIn, pbIn, 0); + h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + + byte[] pbOutBuffer = new byte[64]; + Array.Copy(h.Hash, pbOutBuffer, pbOutBuffer.Length); + + int ibOut = 64 / 2; + Array.Copy(pbOutBuffer, pbOut, ibOut); + int cbToProduce = cbOut - ibOut; + + h.Initialize(); + while(cbToProduce > 64) + { + byte[] pbHash = h.ComputeHash(pbOutBuffer); + Array.Copy(pbHash, pbOutBuffer, 64); + + Array.Copy(pbHash, 0, pbOut, ibOut, 64 / 2); + ibOut += 64 / 2; + cbToProduce -= 64 / 2; + + MemUtil.ZeroByteArray(pbHash); + } + + using(Blake2b hOut = new Blake2b(cbToProduce)) + { + byte[] pbHash = hOut.ComputeHash(pbOutBuffer); + Array.Copy(pbHash, 0, pbOut, ibOut, cbToProduce); + + MemUtil.ZeroByteArray(pbHash); + } + + MemUtil.ZeroByteArray(pbOutBuffer); + } + +#if !ARGON2_G_INLINED + private static ulong BlaMka(ulong x, ulong y) + { + ulong xy = (x & 0xFFFFFFFFUL) * (y & 0xFFFFFFFFUL); + return (x + y + (xy << 1)); + } + + private static void G(ulong[] v, int a, int b, int c, int d) + { + ulong va = v[a], vb = v[b], vc = v[c], vd = v[d]; + + va = BlaMka(va, vb); + vd = MemUtil.RotateRight64(vd ^ va, 32); + vc = BlaMka(vc, vd); + vb = MemUtil.RotateRight64(vb ^ vc, 24); + va = BlaMka(va, vb); + vd = MemUtil.RotateRight64(vd ^ va, 16); + vc = BlaMka(vc, vd); + vb = MemUtil.RotateRight64(vb ^ vc, 63); + + v[a] = va; + v[b] = vb; + v[c] = vc; + v[d] = vd; + } +#else + private static void G(ulong[] v, int a, int b, int c, int d) + { + ulong va = v[a], vb = v[b], vc = v[c], vd = v[d]; + + ulong xy = (va & 0xFFFFFFFFUL) * (vb & 0xFFFFFFFFUL); + va += vb + (xy << 1); + + vd = MemUtil.RotateRight64(vd ^ va, 32); + + xy = (vc & 0xFFFFFFFFUL) * (vd & 0xFFFFFFFFUL); + vc += vd + (xy << 1); + + vb = MemUtil.RotateRight64(vb ^ vc, 24); + + xy = (va & 0xFFFFFFFFUL) * (vb & 0xFFFFFFFFUL); + va += vb + (xy << 1); + + vd = MemUtil.RotateRight64(vd ^ va, 16); + + xy = (vc & 0xFFFFFFFFUL) * (vd & 0xFFFFFFFFUL); + vc += vd + (xy << 1); + + vb = MemUtil.RotateRight64(vb ^ vc, 63); + + v[a] = va; + v[b] = vb; + v[c] = vc; + v[d] = vd; + } +#endif + +#if ARGON2_B2ROUND_ARRAYS + private static void Blake2RoundNoMsg(ulong[] pbR, int[] v) + { + G(pbR, v[0], v[4], v[8], v[12]); + G(pbR, v[1], v[5], v[9], v[13]); + G(pbR, v[2], v[6], v[10], v[14]); + G(pbR, v[3], v[7], v[11], v[15]); + G(pbR, v[0], v[5], v[10], v[15]); + G(pbR, v[1], v[6], v[11], v[12]); + G(pbR, v[2], v[7], v[8], v[13]); + G(pbR, v[3], v[4], v[9], v[14]); + } +#else + private static void Blake2RoundNoMsgCols16i(ulong[] pbR, int i) + { + G(pbR, i, i + 4, i + 8, i + 12); + G(pbR, i + 1, i + 5, i + 9, i + 13); + G(pbR, i + 2, i + 6, i + 10, i + 14); + G(pbR, i + 3, i + 7, i + 11, i + 15); + G(pbR, i, i + 5, i + 10, i + 15); + G(pbR, i + 1, i + 6, i + 11, i + 12); + G(pbR, i + 2, i + 7, i + 8, i + 13); + G(pbR, i + 3, i + 4, i + 9, i + 14); + } + + private static void Blake2RoundNoMsgRows2i(ulong[] pbR, int i) + { + G(pbR, i, i + 32, i + 64, i + 96); + G(pbR, i + 1, i + 33, i + 65, i + 97); + G(pbR, i + 16, i + 48, i + 80, i + 112); + G(pbR, i + 17, i + 49, i + 81, i + 113); + G(pbR, i, i + 33, i + 80, i + 113); + G(pbR, i + 1, i + 48, i + 81, i + 96); + G(pbR, i + 16, i + 49, i + 64, i + 97); + G(pbR, i + 17, i + 32, i + 65, i + 112); + } +#endif + + private static void FillFirstBlocks(Argon2Ctx ctx, byte[] pbBlockHash, + Blake2b h) + { + byte[] pbBlock = new byte[NbBlockSize]; + + for(ulong l = 0; l < ctx.Lanes; ++l) + { + MemUtil.UInt32ToBytesEx(0, pbBlockHash, NbPreHashDigestLength); + MemUtil.UInt32ToBytesEx((uint)l, pbBlockHash, NbPreHashDigestLength + 4); + + Blake2bLong(pbBlock, (int)NbBlockSize, pbBlockHash, + NbPreHashSeedLength, h); + LoadBlock(ctx.Mem, l * ctx.LaneLength * NbBlockSizeInQW, pbBlock); + + MemUtil.UInt32ToBytesEx(1, pbBlockHash, NbPreHashDigestLength); + + Blake2bLong(pbBlock, (int)NbBlockSize, pbBlockHash, + NbPreHashSeedLength, h); + LoadBlock(ctx.Mem, (l * ctx.LaneLength + 1UL) * NbBlockSizeInQW, pbBlock); + } + + MemUtil.ZeroByteArray(pbBlock); + } + + private static ulong IndexAlpha(Argon2Ctx ctx, Argon2ThreadInfo ti, + uint uPseudoRand, bool bSameLane) + { + ulong uRefAreaSize; + if(ti.Pass == 0) + { + if(ti.Slice == 0) + { + Debug.Assert(ti.Index > 0); + uRefAreaSize = ti.Index - 1UL; + } + else + { + if(bSameLane) + uRefAreaSize = ti.Slice * ctx.SegmentLength + + ti.Index - 1UL; + else + uRefAreaSize = ti.Slice * ctx.SegmentLength - + ((ti.Index == 0UL) ? 1UL : 0UL); + } + } + else + { + if(bSameLane) + uRefAreaSize = ctx.LaneLength - ctx.SegmentLength + + ti.Index - 1UL; + else + uRefAreaSize = ctx.LaneLength - ctx.SegmentLength - + ((ti.Index == 0) ? 1UL : 0UL); + } + Debug.Assert(uRefAreaSize <= (ulong)uint.MaxValue); + + ulong uRelPos = uPseudoRand; + uRelPos = (uRelPos * uRelPos) >> 32; + uRelPos = uRefAreaSize - 1UL - ((uRefAreaSize * uRelPos) >> 32); + + ulong uStart = 0; + if(ti.Pass != 0) + uStart = (((ti.Slice + 1UL) == NbSyncPoints) ? 0UL : + ((ti.Slice + 1UL) * ctx.SegmentLength)); + Debug.Assert(uStart <= (ulong)uint.MaxValue); + + Debug.Assert(ctx.LaneLength <= (ulong)uint.MaxValue); + return ((uStart + uRelPos) % ctx.LaneLength); + } + + private static void FillMemoryBlocks(Argon2Ctx ctx) + { + int np = (int)ctx.Lanes; + Argon2ThreadInfo[] v = new Argon2ThreadInfo[np]; + + for(ulong r = 0; r < ctx.TCost; ++r) + { + for(ulong s = 0; s < NbSyncPoints; ++s) + { + for(int l = 0; l < np; ++l) + { + Argon2ThreadInfo ti = new Argon2ThreadInfo(); + ti.Context = ctx; + + ti.Pass = r; + ti.Lane = (ulong)l; + ti.Slice = s; + + if(!ThreadPool.QueueUserWorkItem(FillSegmentThr, ti)) + { + Debug.Assert(false); + throw new OutOfMemoryException(); + } + + v[l] = ti; + } + + for(int l = 0; l < np; ++l) + v[l].Finished.WaitOne(); + } + } + } + + private static void FillSegmentThr(object o) + { + Argon2ThreadInfo ti = (o as Argon2ThreadInfo); + if(ti == null) { Debug.Assert(false); return; } + + try + { + Argon2Ctx ctx = ti.Context; + if(ctx == null) { Debug.Assert(false); return; } + + Debug.Assert(ctx.Version >= MinVersion); + bool bCanXor = (ctx.Version >= 0x13U); + + ulong uStart = 0; + if((ti.Pass == 0) && (ti.Slice == 0)) uStart = 2; + + ulong uCur = (ti.Lane * ctx.LaneLength) + (ti.Slice * + ctx.SegmentLength) + uStart; + + ulong uPrev = (((uCur % ctx.LaneLength) == 0) ? + (uCur + ctx.LaneLength - 1UL) : (uCur - 1UL)); + + ulong[] pbR = new ulong[NbBlockSizeInQW]; + ulong[] pbTmp = new ulong[NbBlockSizeInQW]; + + for(ulong i = uStart; i < ctx.SegmentLength; ++i) + { + if((uCur % ctx.LaneLength) == 1) + uPrev = uCur - 1UL; + + ulong uPseudoRand = ctx.Mem[uPrev * NbBlockSizeInQW]; + ulong uRefLane = (uPseudoRand >> 32) % ctx.Lanes; + if((ti.Pass == 0) && (ti.Slice == 0)) + uRefLane = ti.Lane; + + ti.Index = i; + ulong uRefIndex = IndexAlpha(ctx, ti, (uint)uPseudoRand, + (uRefLane == ti.Lane)); + + ulong uRefBlockIndex = (ctx.LaneLength * uRefLane + + uRefIndex) * NbBlockSizeInQW; + ulong uCurBlockIndex = uCur * NbBlockSizeInQW; + + FillBlock(ctx.Mem, uPrev * NbBlockSizeInQW, uRefBlockIndex, + uCurBlockIndex, ((ti.Pass != 0) && bCanXor), pbR, pbTmp); + + ++uCur; + ++uPrev; + } + + MemUtil.ZeroArray(pbR); + MemUtil.ZeroArray(pbTmp); + } + catch(Exception) { Debug.Assert(false); } + + try { ti.Finished.Set(); } + catch(Exception) { Debug.Assert(false); } + } + +#if ARGON2_B2ROUND_ARRAYS + private static void InitB2RoundIndexArrays() + { + int[][] vCols = g_vFBCols; + if(vCols == null) + { + vCols = new int[8][]; + Debug.Assert(vCols.Length == 8); + int e = 0; + for(int i = 0; i < 8; ++i) + { + vCols[i] = new int[16]; + for(int j = 0; j < 16; ++j) + { + vCols[i][j] = e; + ++e; + } + } + + g_vFBCols = vCols; + } + + int[][] vRows = g_vFBRows; + if(vRows == null) + { + vRows = new int[8][]; + for(int i = 0; i < 8; ++i) + { + vRows[i] = new int[16]; + for(int j = 0; j < 16; ++j) + { + int jh = j / 2; + vRows[i][j] = (2 * i) + (16 * jh) + (j & 1); + } + } + + g_vFBRows = vRows; + } + } +#endif + + private static void FillBlock(ulong[] pMem, ulong uPrev, ulong uRef, + ulong uNext, bool bXor, ulong[] pbR, ulong[] pbTmp) + { + CopyBlock(pbR, 0, pMem, uRef); + XorBlock(pbR, 0, pMem, uPrev); + CopyBlock(pbTmp, 0, pbR, 0); + if(bXor) XorBlock(pbTmp, 0, pMem, uNext); + +#if ARGON2_B2ROUND_ARRAYS + int[][] vCols = g_vFBCols; + int[][] vRows = g_vFBRows; + for(int i = 0; i < 8; ++i) + Blake2RoundNoMsg(pbR, vCols[i]); + for(int i = 0; i < 8; ++i) + Blake2RoundNoMsg(pbR, vRows[i]); +#else + for(int i = 0; i < (8 * 16); i += 16) + Blake2RoundNoMsgCols16i(pbR, i); + for(int i = 0; i < (8 * 2); i += 2) + Blake2RoundNoMsgRows2i(pbR, i); +#endif + + CopyBlock(pMem, uNext, pbTmp, 0); + XorBlock(pMem, uNext, pbR, 0); + } + + private static byte[] FinalHash(Argon2Ctx ctx, int cbOut, Blake2b h) + { + ulong[] pqBlockHash = new ulong[NbBlockSizeInQW]; + CopyBlock(pqBlockHash, 0, ctx.Mem, (ctx.LaneLength - 1UL) * + NbBlockSizeInQW); + for(ulong l = 1; l < ctx.Lanes; ++l) + XorBlock(pqBlockHash, 0, ctx.Mem, (l * ctx.LaneLength + + ctx.LaneLength - 1UL) * NbBlockSizeInQW); + + byte[] pbBlockHashBytes = new byte[NbBlockSize]; + StoreBlock(pbBlockHashBytes, pqBlockHash); + + byte[] pbOut = new byte[cbOut]; + Blake2bLong(pbOut, cbOut, pbBlockHashBytes, (int)NbBlockSize, h); + + MemUtil.ZeroArray(pqBlockHash); + MemUtil.ZeroByteArray(pbBlockHashBytes); + return pbOut; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.cs new file mode 100644 index 00000000..69416ad2 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/Argon2Kdf.cs @@ -0,0 +1,144 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public sealed partial class Argon2Kdf : KdfEngine + { + private static readonly PwUuid g_uuid = new PwUuid(new byte[] { + 0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B, + 0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C }); + + public const string ParamSalt = "S"; // Byte[] + public const string ParamParallelism = "P"; // UInt32 + public const string ParamMemory = "M"; // UInt64 + public const string ParamIterations = "I"; // UInt64 + public const string ParamVersion = "V"; // UInt32 + public const string ParamSecretKey = "K"; // Byte[] + public const string ParamAssocData = "A"; // Byte[] + + private const uint MinVersion = 0x10; + private const uint MaxVersion = 0x13; + + private const int MinSalt = 8; + private const int MaxSalt = int.MaxValue; // .NET limit; 2^32 - 1 in spec + + internal const ulong MinIterations = 1; + internal const ulong MaxIterations = uint.MaxValue; + + internal const ulong MinMemory = 1024 * 8; // For parallelism = 1 + // internal const ulong MaxMemory = (ulong)uint.MaxValue * 1024UL; // Spec + internal const ulong MaxMemory = int.MaxValue; // .NET limit + + internal const uint MinParallelism = 1; + internal const uint MaxParallelism = (1 << 24) - 1; + + internal const ulong DefaultIterations = 2; + internal const ulong DefaultMemory = 1024 * 1024; // 1 MB + internal const uint DefaultParallelism = 2; + + public override PwUuid Uuid + { + get { return g_uuid; } + } + + public override string Name + { + get { return "Argon2"; } + } + + public Argon2Kdf() + { + } + + public override KdfParameters GetDefaultParameters() + { + KdfParameters p = base.GetDefaultParameters(); + + p.SetUInt32(ParamVersion, MaxVersion); + + p.SetUInt64(ParamIterations, DefaultIterations); + p.SetUInt64(ParamMemory, DefaultMemory); + p.SetUInt32(ParamParallelism, DefaultParallelism); + + return p; + } + + public override void Randomize(KdfParameters p) + { + if(p == null) { Debug.Assert(false); return; } + Debug.Assert(g_uuid.Equals(p.KdfUuid)); + + byte[] pb = CryptoRandom.Instance.GetRandomBytes(32); + p.SetByteArray(ParamSalt, pb); + } + + public override byte[] Transform(byte[] pbMsg, KdfParameters p) + { + if(pbMsg == null) throw new ArgumentNullException("pbMsg"); + if(p == null) throw new ArgumentNullException("p"); + + byte[] pbSalt = p.GetByteArray(ParamSalt); + if(pbSalt == null) + throw new ArgumentNullException("p.Salt"); + if((pbSalt.Length < MinSalt) || (pbSalt.Length > MaxSalt)) + throw new ArgumentOutOfRangeException("p.Salt"); + + uint uPar = p.GetUInt32(ParamParallelism, 0); + if((uPar < MinParallelism) || (uPar > MaxParallelism)) + throw new ArgumentOutOfRangeException("p.Parallelism"); + + ulong uMem = p.GetUInt64(ParamMemory, 0); + if((uMem < MinMemory) || (uMem > MaxMemory)) + throw new ArgumentOutOfRangeException("p.Memory"); + + ulong uIt = p.GetUInt64(ParamIterations, 0); + if((uIt < MinIterations) || (uIt > MaxIterations)) + throw new ArgumentOutOfRangeException("p.Iterations"); + + uint v = p.GetUInt32(ParamVersion, 0); + if((v < MinVersion) || (v > MaxVersion)) + throw new ArgumentOutOfRangeException("p.Version"); + + byte[] pbSecretKey = p.GetByteArray(ParamSecretKey); + byte[] pbAssocData = p.GetByteArray(ParamAssocData); + + byte[] pbRet = Argon2d(pbMsg, pbSalt, uPar, uMem, uIt, + 32, v, pbSecretKey, pbAssocData); + + if(uMem > (100UL * 1024UL * 1024UL)) GC.Collect(); + return pbRet; + } + + public override KdfParameters GetBestParameters(uint uMilliseconds) + { + KdfParameters p = GetDefaultParameters(); + Randomize(p); + + MaximizeParamUInt64(p, ParamIterations, MinIterations, + MaxIterations, uMilliseconds, true); + return p; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfEngine.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfEngine.cs new file mode 100644 index 00000000..74d0dd25 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfEngine.cs @@ -0,0 +1,142 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public abstract class KdfEngine + { + public abstract PwUuid Uuid + { + get; + } + + public abstract string Name + { + get; + } + + public virtual KdfParameters GetDefaultParameters() + { + return new KdfParameters(this.Uuid); + } + + /// + /// Generate random seeds and store them in . + /// + public virtual void Randomize(KdfParameters p) + { + Debug.Assert(p != null); + Debug.Assert(p.KdfUuid.Equals(this.Uuid)); + } + + public abstract byte[] Transform(byte[] pbMsg, KdfParameters p); + + public virtual KdfParameters GetBestParameters(uint uMilliseconds) + { + throw new NotImplementedException(); + } + + protected void MaximizeParamUInt64(KdfParameters p, string strName, + ulong uMin, ulong uMax, uint uMilliseconds, bool bInterpSearch) + { + if(p == null) { Debug.Assert(false); return; } + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return; } + if(uMin > uMax) { Debug.Assert(false); return; } + + if(uMax > (ulong.MaxValue >> 1)) + { + Debug.Assert(false); + uMax = ulong.MaxValue >> 1; + + if(uMin > uMax) { p.SetUInt64(strName, uMin); return; } + } + + byte[] pbMsg = new byte[32]; + for(int i = 0; i < pbMsg.Length; ++i) pbMsg[i] = (byte)i; + + ulong uLow = uMin; + ulong uHigh = uMin + 1UL; + long tLow = 0; + long tHigh = 0; + long tTarget = (long)uMilliseconds; + + // Determine range + while(uHigh <= uMax) + { + p.SetUInt64(strName, uHigh); + + // GC.Collect(); + Stopwatch sw = Stopwatch.StartNew(); + Transform(pbMsg, p); + sw.Stop(); + + tHigh = sw.ElapsedMilliseconds; + if(tHigh > tTarget) break; + + uLow = uHigh; + tLow = tHigh; + uHigh <<= 1; + } + if(uHigh > uMax) { uHigh = uMax; tHigh = 0; } + if(uLow > uHigh) uLow = uHigh; // Skips to end + + // Find optimal number of iterations + while((uHigh - uLow) >= 2UL) + { + ulong u = (uHigh + uLow) >> 1; // Binary search + // Interpolation search, if possible + if(bInterpSearch && (tLow > 0) && (tHigh > tTarget) && + (tLow <= tTarget)) + { + u = uLow + (((uHigh - uLow) * (ulong)(tTarget - tLow)) / + (ulong)(tHigh - tLow)); + if((u >= uLow) && (u <= uHigh)) + { + u = Math.Max(u, uLow + 1UL); + u = Math.Min(u, uHigh - 1UL); + } + else + { + Debug.Assert(false); + u = (uHigh + uLow) >> 1; + } + } + + p.SetUInt64(strName, u); + + // GC.Collect(); + Stopwatch sw = Stopwatch.StartNew(); + Transform(pbMsg, p); + sw.Stop(); + + long t = sw.ElapsedMilliseconds; + if(t == tTarget) { uLow = u; break; } + else if(t > tTarget) { uHigh = u; tHigh = t; } + else { uLow = u; tLow = t; } + } + + p.SetUInt64(strName, uLow); + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfParameters.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfParameters.cs new file mode 100644 index 00000000..3723b78f --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfParameters.cs @@ -0,0 +1,80 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; + +using KeePassLib.Collections; +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public sealed class KdfParameters : VariantDictionary + { + private const string ParamUuid = @"$UUID"; + + private readonly PwUuid m_puKdf; + public PwUuid KdfUuid + { + get { return m_puKdf; } + } + + public KdfParameters(PwUuid puKdf) + { + if(puKdf == null) throw new ArgumentNullException("puKdf"); + + m_puKdf = puKdf; + SetByteArray(ParamUuid, puKdf.UuidBytes); + } + + /// + /// Unsupported. + /// + public override object Clone() + { + throw new NotSupportedException(); + } + + public static byte[] SerializeExt(KdfParameters p) + { + return VariantDictionary.Serialize(p); + } + + public static KdfParameters DeserializeExt(byte[] pb) + { + VariantDictionary d = VariantDictionary.Deserialize(pb); + if(d == null) { Debug.Assert(false); return null; } + + byte[] pbUuid = d.GetByteArray(ParamUuid); + if((pbUuid == null) || (pbUuid.Length != (int)PwUuid.UuidSize)) + { + Debug.Assert(false); + return null; + } + + PwUuid pu = new PwUuid(pbUuid); + KdfParameters p = new KdfParameters(pu); + d.CopyTo(p); + return p; + } + } +} diff --git a/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfPool.cs b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfPool.cs new file mode 100644 index 00000000..08979e23 --- /dev/null +++ b/src/KeePassLib2Android/Cryptography/KeyDerivation/KdfPool.cs @@ -0,0 +1,96 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +using KeePassLib.Utility; + +namespace KeePassLib.Cryptography.KeyDerivation +{ + public static class KdfPool + { + private static List g_l = new List(); + + public static IEnumerable Engines + { + get + { + EnsureInitialized(); + return g_l; + } + } + + private static void EnsureInitialized() + { + if(g_l.Count > 0) return; + + g_l.Add(new AesKdf()); + g_l.Add(new Argon2Kdf()); + } + + internal static KdfParameters GetDefaultParameters() + { + EnsureInitialized(); + return g_l[0].GetDefaultParameters(); + } + + public static KdfEngine Get(PwUuid pu) + { + if(pu == null) { Debug.Assert(false); return null; } + + EnsureInitialized(); + + foreach(KdfEngine kdf in g_l) + { + if(pu.Equals(kdf.Uuid)) return kdf; + } + + return null; + } + + public static KdfEngine Get(string strName) + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return null; } + + EnsureInitialized(); + + foreach(KdfEngine kdf in g_l) + { + if(strName.Equals(kdf.Name, StrUtil.CaseIgnoreCmp)) return kdf; + } + + return null; + } + + public static void Add(KdfEngine kdf) + { + if(kdf == null) { Debug.Assert(false); return; } + + EnsureInitialized(); + + if(Get(kdf.Uuid) != null) { Debug.Assert(false); return; } + if(Get(kdf.Name) != null) { Debug.Assert(false); return; } + + g_l.Add(kdf); + } + } +} diff --git a/src/KeePassLib2Android/KeePassLib2Android.csproj b/src/KeePassLib2Android/KeePassLib2Android.csproj index 763e2040..6b2ea7f7 100644 --- a/src/KeePassLib2Android/KeePassLib2Android.csproj +++ b/src/KeePassLib2Android/KeePassLib2Android.csproj @@ -60,6 +60,18 @@ + + + + + + + + + + + + @@ -87,7 +99,6 @@ - @@ -124,9 +135,13 @@ + Component + + + @@ -134,8 +149,6 @@ - - @@ -144,6 +157,7 @@ + diff --git a/src/KeePassLib2Android/Keys/CompositeKey.cs b/src/KeePassLib2Android/Keys/CompositeKey.cs index 0b31eb3d..673d96dc 100644 --- a/src/KeePassLib2Android/Keys/CompositeKey.cs +++ b/src/KeePassLib2Android/Keys/CompositeKey.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,22 +18,16 @@ */ using System; -using System.Text; using System.Collections.Generic; using System.Diagnostics; -using System.IO; -using System.Security.Cryptography; - -#if KeePassRT -using Org.BouncyCastle.Crypto.Engines; -using Org.BouncyCastle.Crypto.Parameters; -#endif +using System.Text; +using KeePassLib.Cryptography; +using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Native; using KeePassLib.Resources; using KeePassLib.Security; using KeePassLib.Utility; -using keepass2android; namespace KeePassLib.Keys { @@ -109,7 +103,6 @@ namespace KeePassLib.Keys return m_vUserKeys.Remove(pKey); } -#if !KeePassRT /// /// Test whether the composite key contains a specific type of /// user keys (password, key file, ...). If at least one user @@ -125,8 +118,15 @@ namespace KeePassLib.Keys foreach(IUserKey pKey in m_vUserKeys) { + if(pKey == null) { Debug.Assert(false); continue; } + +#if KeePassUAP + if(pKey.GetType() == tUserKeyType) + return true; +#else if(tUserKeyType.IsInstanceOfType(pKey)) return true; +#endif } return false; @@ -145,8 +145,15 @@ namespace KeePassLib.Keys foreach(IUserKey pKey in m_vUserKeys) { + if(pKey == null) { Debug.Assert(false); continue; } + +#if KeePassUAP + if(pKey.GetType() == tUserKeyType) + return pKey; +#else if(tUserKeyType.IsInstanceOfType(pKey)) return pKey; +#endif } return null; @@ -156,8 +163,6 @@ namespace KeePassLib.Keys { return (T) GetUserKey(typeof (T)); } -#endif - /// /// Creates the composite key from the supplied user key sources (password, /// key file, user account, computer ID, etc.). @@ -167,21 +172,31 @@ namespace KeePassLib.Keys ValidateUserKeys(); // Concatenate user key data - MemoryStream ms = new MemoryStream(); + List lData = new List(); + int cbData = 0; foreach(IUserKey pKey in m_vUserKeys) { ProtectedBinary b = pKey.KeyData; if(b != null) { byte[] pbKeyData = b.ReadData(); - ms.Write(pbKeyData, 0, pbKeyData.Length); - MemUtil.ZeroByteArray(pbKeyData); + lData.Add(pbKeyData); + cbData += pbKeyData.Length; } } - SHA256Managed sha256 = new SHA256Managed(); - byte[] pbHash = sha256.ComputeHash(ms.ToArray()); - ms.Close(); + byte[] pbAllData = new byte[cbData]; + int p = 0; + foreach(byte[] pbData in lData) + { + Array.Copy(pbData, 0, pbAllData, p, pbData.Length); + p += pbData.Length; + MemUtil.ZeroByteArray(pbData); + } + Debug.Assert(p == cbData); + + byte[] pbHash = CryptoUtil.HashSha256(pbAllData); + MemUtil.ZeroByteArray(pbAllData); return pbHash; } @@ -192,21 +207,13 @@ namespace KeePassLib.Keys byte[] pbThis = CreateRawCompositeKey32(); byte[] pbOther = ckOther.CreateRawCompositeKey32(); bool bResult = MemUtil.ArraysEqual(pbThis, pbOther); - Array.Clear(pbOther, 0, pbOther.Length); - Array.Clear(pbThis, 0, pbThis.Length); + MemUtil.ZeroByteArray(pbOther); + MemUtil.ZeroByteArray(pbThis); return bResult; } - /// - /// Generate a 32-bit wide key out of the composite key. - /// - /// Seed used in the key transformation - /// rounds. Must be a byte array containing exactly 32 bytes; must - /// not be null. - /// Number of key transformation rounds. - /// Returns a protected binary object that contains the - /// resulting 32-bit wide key. + [Obsolete] public ProtectedBinary GenerateKey32(byte[] pbKeySeed32, ulong uNumRounds) { Debug.Assert(pbKeySeed32 != null); @@ -214,18 +221,43 @@ namespace KeePassLib.Keys Debug.Assert(pbKeySeed32.Length == 32); if(pbKeySeed32.Length != 32) throw new ArgumentException("pbKeySeed32"); + AesKdf kdf = new AesKdf(); + KdfParameters p = kdf.GetDefaultParameters(); + p.SetUInt64(AesKdf.ParamRounds, uNumRounds); + p.SetByteArray(AesKdf.ParamSeed, pbKeySeed32); + + return GenerateKey32(p); + } + + /// + /// Generate a 32-byte (256-bit) key from the composite key. + /// + public ProtectedBinary GenerateKey32(KdfParameters p) + { + if(p == null) { Debug.Assert(false); throw new ArgumentNullException("p"); } + byte[] pbRaw32 = CreateRawCompositeKey32(); if((pbRaw32 == null) || (pbRaw32.Length != 32)) { Debug.Assert(false); return null; } - byte[] pbTrf32 = TransformKey(pbRaw32, pbKeySeed32, uNumRounds); - if((pbTrf32 == null) || (pbTrf32.Length != 32)) - { Debug.Assert(false); return null; } + KdfEngine kdf = KdfPool.Get(p.KdfUuid); + if(kdf == null) // CryptographicExceptions are translated to "file corrupted" + throw new Exception(KLRes.UnknownKdf + MessageService.NewParagraph + + KLRes.FileNewVerOrPlgReq + MessageService.NewParagraph + + "UUID: " + p.KdfUuid.ToHexString() + "."); + + byte[] pbTrf32 = kdf.Transform(pbRaw32, p); + if(pbTrf32 == null) { Debug.Assert(false); return null; } + + if(pbTrf32.Length != 32) + { + Debug.Assert(false); + pbTrf32 = CryptoUtil.HashSha256(pbTrf32); + } ProtectedBinary pbRet = new ProtectedBinary(true, pbTrf32); MemUtil.ZeroByteArray(pbTrf32); MemUtil.ZeroByteArray(pbRaw32); - return pbRet; } @@ -245,192 +277,6 @@ namespace KeePassLib.Keys throw new InvalidOperationException(); } } - - /// - /// Transform the current key uNumRounds times. - /// - /// The original key which will be transformed. - /// This parameter won't be modified. - /// Seed used for key transformations. Must not - /// be null. This parameter won't be modified. - /// Transformation count. - /// 256-bit transformed key. - private static byte[] TransformKey(byte[] pbOriginalKey32, byte[] pbKeySeed32, - ulong uNumRounds) - { - Debug.Assert((pbOriginalKey32 != null) && (pbOriginalKey32.Length == 32)); - if (pbOriginalKey32 == null) - throw new ArgumentNullException("pbOriginalKey32"); - if (pbOriginalKey32.Length != 32) - throw new ArgumentException(); - - Debug.Assert((pbKeySeed32 != null) && (pbKeySeed32.Length == 32)); - if (pbKeySeed32 == null) - throw new ArgumentNullException("pbKeySeed32"); - if (pbKeySeed32.Length != 32) - throw new ArgumentException(); - - byte[] pbNewKey = new byte[32]; - Array.Copy(pbOriginalKey32, pbNewKey, pbNewKey.Length); - - // Try to use the native library first - Stopwatch sw = new Stopwatch(); - sw.Start(); - if (NativeLib.TransformKey256(pbNewKey, pbKeySeed32, uNumRounds)) - { - sw.Stop(); - Kp2aLog.Log("Native transform:" +sw.ElapsedMilliseconds+"ms"); - return pbNewKey; - } - - sw.Restart(); - if(TransformKeyManaged(pbNewKey, pbKeySeed32, uNumRounds) == false) - return null; - sw.Stop(); - Kp2aLog.Log("Managed transform:" +sw.ElapsedMilliseconds+"ms"); - - SHA256Managed sha256 = new SHA256Managed(); - return sha256.ComputeHash(pbNewKey); - } - - public static bool TransformKeyManaged(byte[] pbNewKey32, byte[] pbKeySeed32, - ulong uNumRounds) - { -#if KeePassRT - KeyParameter kp = new KeyParameter(pbKeySeed32); - AesEngine aes = new AesEngine(); - aes.Init(true, kp); - - for(ulong i = 0; i < uNumRounds; ++i) - { - aes.ProcessBlock(pbNewKey32, 0, pbNewKey32, 0); - aes.ProcessBlock(pbNewKey32, 16, pbNewKey32, 16); - } -#else - byte[] pbIV = new byte[16]; - Array.Clear(pbIV, 0, pbIV.Length); - - RijndaelManaged r = new RijndaelManaged(); - if(r.BlockSize != 128) // AES block size - { - Debug.Assert(false); - r.BlockSize = 128; - } - - r.IV = pbIV; - r.Mode = CipherMode.ECB; - r.KeySize = 256; - r.Key = pbKeySeed32; - ICryptoTransform iCrypt = r.CreateEncryptor(); - - // !iCrypt.CanReuseTransform -- doesn't work with Mono - if((iCrypt == null) || (iCrypt.InputBlockSize != 16) || - (iCrypt.OutputBlockSize != 16)) - { - Debug.Assert(false, "Invalid ICryptoTransform."); - Debug.Assert((iCrypt.InputBlockSize == 16), "Invalid input block size!"); - Debug.Assert((iCrypt.OutputBlockSize == 16), "Invalid output block size!"); - return false; - } - - for(ulong i = 0; i < uNumRounds; ++i) - { - iCrypt.TransformBlock(pbNewKey32, 0, 16, pbNewKey32, 0); - iCrypt.TransformBlock(pbNewKey32, 16, 16, pbNewKey32, 16); - } -#endif - - return true; - } - - /// - /// Benchmark the TransformKey method. Within - /// ms, random keys will be transformed - /// and the number of performed transformations are returned. - /// - /// Test duration in ms. - /// Stepping. - /// should be a prime number. For fast processors - /// (PCs) a value of 3001 is recommended, for slower processors (PocketPC) - /// a value of 401 is recommended. - /// Number of transformations performed in the specified - /// amount of time. Maximum value is uint.MaxValue. - public static ulong TransformKeyBenchmark(uint uMilliseconds, ulong uStep) - { - ulong uRounds; - - // Try native method - if(NativeLib.TransformKeyBenchmark256(uMilliseconds, out uRounds)) - return uRounds; - - byte[] pbKey = new byte[32]; - byte[] pbNewKey = new byte[32]; - for(int i = 0; i < pbKey.Length; ++i) - { - pbKey[i] = (byte)i; - pbNewKey[i] = (byte)i; - } - -#if KeePassRT - KeyParameter kp = new KeyParameter(pbKey); - AesEngine aes = new AesEngine(); - aes.Init(true, kp); -#else - byte[] pbIV = new byte[16]; - Array.Clear(pbIV, 0, pbIV.Length); - - RijndaelManaged r = new RijndaelManaged(); - if(r.BlockSize != 128) // AES block size - { - Debug.Assert(false); - r.BlockSize = 128; - } - - r.IV = pbIV; - r.Mode = CipherMode.ECB; - r.KeySize = 256; - r.Key = pbKey; - ICryptoTransform iCrypt = r.CreateEncryptor(); - - // !iCrypt.CanReuseTransform -- doesn't work with Mono - if((iCrypt == null) || (iCrypt.InputBlockSize != 16) || - (iCrypt.OutputBlockSize != 16)) - { - Debug.Assert(false, "Invalid ICryptoTransform."); - Debug.Assert(iCrypt.InputBlockSize == 16, "Invalid input block size!"); - Debug.Assert(iCrypt.OutputBlockSize == 16, "Invalid output block size!"); - return PwDefs.DefaultKeyEncryptionRounds; - } -#endif - - uRounds = 0; - int tStart = Environment.TickCount; - while(true) - { - for(ulong j = 0; j < uStep; ++j) - { -#if KeePassRT - aes.ProcessBlock(pbNewKey, 0, pbNewKey, 0); - aes.ProcessBlock(pbNewKey, 16, pbNewKey, 16); -#else - iCrypt.TransformBlock(pbNewKey, 0, 16, pbNewKey, 0); - iCrypt.TransformBlock(pbNewKey, 16, 16, pbNewKey, 16); -#endif - } - - uRounds += uStep; - if(uRounds < uStep) // Overflow check - { - uRounds = ulong.MaxValue; - break; - } - - uint tElapsed = (uint)(Environment.TickCount - tStart); - if(tElapsed > uMilliseconds) break; - } - - return uRounds; - } } public sealed class InvalidCompositeKeyException : Exception diff --git a/src/KeePassLib2Android/Keys/KcpKeyFile.cs b/src/KeePassLib2Android/Keys/KcpKeyFile.cs index d8b200b5..da59571f 100644 --- a/src/KeePassLib2Android/Keys/KcpKeyFile.cs +++ b/src/KeePassLib2Android/Keys/KcpKeyFile.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -20,12 +18,15 @@ */ using System; -using System.Text; -using System.IO; -using System.Xml; -using System.Security; -using System.Security.Cryptography; using System.Diagnostics; +using System.IO; +using System.Security; +using System.Text; +using System.Xml; + +#if !KeePassUAP +using System.Security.Cryptography; +#endif using KeePassLib.Cryptography; using KeePassLib.Resources; @@ -103,12 +104,12 @@ namespace KeePassLib.Keys if (pbFileData == null) throw new Java.IO.FileNotFoundException(); m_pbFileData = new ProtectedBinary(true, pbFileData); - if (bThrowIfDbFile && (pbFileData.Length >= 8)) + 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) && + if(((uSig1 == KdbxFile.FileSignature1) && (uSig2 == KdbxFile.FileSignature2)) || ((uSig1 == KdbxFile.FileSignaturePreRelease1) && (uSig2 == KdbxFile.FileSignaturePreRelease2)) || @@ -122,9 +123,9 @@ namespace KeePassLib.Keys } byte[] pbKey = LoadXmlKeyFile(pbFileData); - if (pbKey == null) pbKey = LoadKeyFile(pbFileData); + if(pbKey == null) pbKey = LoadKeyFile(pbFileData); - if (pbKey == null) throw new InvalidOperationException(); + if(pbKey == null) throw new InvalidOperationException(); m_ioc = iocKeyFile; m_pbKeyData = new ProtectedBinary(true, pbKey); @@ -137,13 +138,13 @@ namespace KeePassLib.Keys byte[] pbFileData = IOConnection.ReadFile(iocFile); Construct(pbFileData, iocFile, bThrowIfDbFile); } - // public void Clear() // { // m_strPath = string.Empty; // m_pbKeyData = null; // } + private static byte[] LoadKeyFile(byte[] pbFileData) { if(pbFileData == null) { Debug.Assert(false); return null; } @@ -155,10 +156,7 @@ namespace KeePassLib.Keys else if(iLength == 64) pbKey = LoadHexKey32(pbFileData); if(pbKey == null) - { - SHA256Managed sha256 = new SHA256Managed(); - pbKey = sha256.ComputeHash(pbFileData); - } + pbKey = CryptoUtil.HashSha256(pbFileData); return pbKey; } @@ -178,12 +176,15 @@ namespace KeePassLib.Keys try { - string strHex = StrUtil.Utf8.GetString(pbFileData, 0, 64); - if(!StrUtil.IsHexString(strHex, true)) return null; + if(!StrUtil.IsHexString(pbFileData, true)) return null; + string strHex = StrUtil.Utf8.GetString(pbFileData); byte[] pbKey = MemUtil.HexStringToByteArray(strHex); if((pbKey == null) || (pbKey.Length != 32)) + { + Debug.Assert(false); return null; + } return pbKey; } @@ -211,13 +212,13 @@ namespace KeePassLib.Keys pbFinalKey32 = pbKey32; else { - MemoryStream ms = new MemoryStream(); - ms.Write(pbAdditionalEntropy, 0, pbAdditionalEntropy.Length); - ms.Write(pbKey32, 0, 32); + using(MemoryStream ms = new MemoryStream()) + { + MemUtil.Write(ms, pbAdditionalEntropy); + MemUtil.Write(ms, pbKey32); - SHA256Managed sha256 = new SHA256Managed(); - pbFinalKey32 = sha256.ComputeHash(ms.ToArray()); - ms.Close(); + pbFinalKey32 = CryptoUtil.HashSha256(ms.ToArray()); + } } CreateXmlKeyFile(strFilePath, pbFinalKey32); @@ -292,7 +293,15 @@ namespace KeePassLib.Keys 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"); @@ -334,6 +343,6 @@ namespace KeePassLib.Keys public void ResetIoc(IOConnectionInfo newIoc) { m_ioc = newIoc; - } } } +} diff --git a/src/KeePassLib2Android/Keys/KcpPassword.cs b/src/KeePassLib2Android/Keys/KcpPassword.cs index 22300971..4de3ecdb 100644 --- a/src/KeePassLib2Android/Keys/KcpPassword.cs +++ b/src/KeePassLib2Android/Keys/KcpPassword.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,10 +18,10 @@ */ using System; -using System.Text; using System.Diagnostics; -using System.Security.Cryptography; +using System.Text; +using KeePassLib.Cryptography; using KeePassLib.Security; using KeePassLib.Utility; @@ -68,8 +68,11 @@ namespace KeePassLib.Keys Debug.Assert(pbPasswordUtf8 != null); if(pbPasswordUtf8 == null) throw new ArgumentNullException("pbPasswordUtf8"); - SHA256Managed sha256 = new SHA256Managed(); - byte[] pbRaw = sha256.ComputeHash(pbPasswordUtf8); +#if (DEBUG && !KeePassLibSD) + Debug.Assert(ValidatePassword(pbPasswordUtf8)); +#endif + + byte[] pbRaw = CryptoUtil.HashSha256(pbPasswordUtf8); m_psPassword = new ProtectedString(true, pbPasswordUtf8); m_pbKeyData = new ProtectedBinary(true, pbRaw); @@ -80,5 +83,19 @@ namespace KeePassLib.Keys // m_psPassword = null; // m_pbKeyData = null; // } + +#if (DEBUG && !KeePassLibSD) + private static bool ValidatePassword(byte[] pb) + { + try + { + string str = StrUtil.Utf8.GetString(pb); + return str.IsNormalized(NormalizationForm.FormC); + } + catch(Exception) { Debug.Assert(false); } + + return false; +} +#endif } } diff --git a/src/KeePassLib2Android/Keys/KcpUserAccount.cs b/src/KeePassLib2Android/Keys/KcpUserAccount.cs index 0baebd7c..3408d68c 100644 --- a/src/KeePassLib2Android/Keys/KcpUserAccount.cs +++ b/src/KeePassLib2Android/Keys/KcpUserAccount.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll @@ -20,9 +20,13 @@ */ using System; -using System.Security; -using System.Security.Cryptography; +using System.Diagnostics; using System.IO; +using System.Security; + +#if !KeePassUAP +using System.Security.Cryptography; +#endif using KeePassLib.Cryptography; using KeePassLib.Resources; diff --git a/src/KeePassLib2Android/Keys/KeyProvider.cs b/src/KeePassLib2Android/Keys/KeyProvider.cs index a40a08a0..68908446 100644 --- a/src/KeePassLib2Android/Keys/KeyProvider.cs +++ b/src/KeePassLib2Android/Keys/KeyProvider.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Keys/KeyProviderPool.cs b/src/KeePassLib2Android/Keys/KeyProviderPool.cs index 925c712e..a90788e5 100644 --- a/src/KeePassLib2Android/Keys/KeyProviderPool.cs +++ b/src/KeePassLib2Android/Keys/KeyProviderPool.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Keys/KeyValidator.cs b/src/KeePassLib2Android/Keys/KeyValidator.cs index ce54172c..bb9eb2ff 100644 --- a/src/KeePassLib2Android/Keys/KeyValidator.cs +++ b/src/KeePassLib2Android/Keys/KeyValidator.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Keys/KeyValidatorPool.cs b/src/KeePassLib2Android/Keys/KeyValidatorPool.cs index f50e4d1b..17137676 100644 --- a/src/KeePassLib2Android/Keys/KeyValidatorPool.cs +++ b/src/KeePassLib2Android/Keys/KeyValidatorPool.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Keys/UserKeyType.cs b/src/KeePassLib2Android/Keys/UserKeyType.cs index 02dc94ba..ecd307d2 100644 --- a/src/KeePassLib2Android/Keys/UserKeyType.cs +++ b/src/KeePassLib2Android/Keys/UserKeyType.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Native/NativeLib.cs b/src/KeePassLib2Android/Native/NativeLib.cs index deb701b2..e4e6cbb5 100644 --- a/src/KeePassLib2Android/Native/NativeLib.cs +++ b/src/KeePassLib2Android/Native/NativeLib.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,12 +19,19 @@ using System; using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Threading; using System.Diagnostics; -using Android.Util; -using KeePassLib.Utility; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using Java.Text; using keepass2android; +#if !KeePassUAP +using System.IO; +using System.Threading; +#endif + +using KeePassLib.Utility; namespace KeePassLib.Native { @@ -48,6 +53,61 @@ namespace KeePassLib.Native set { m_bAllowNative = value; } } + private static int? g_oiPointerSize = null; + /// + /// Size of a native pointer (in bytes). + /// + public static int PointerSize + { + get + { + if(!g_oiPointerSize.HasValue) +#if KeePassUAP + g_oiPointerSize = Marshal.SizeOf(); +#else + g_oiPointerSize = Marshal.SizeOf(typeof(IntPtr)); +#endif + return g_oiPointerSize.Value; + } + } + + private static ulong? m_ouMonoVersion = null; + public static ulong MonoVersion + { + get + { + if(m_ouMonoVersion.HasValue) return m_ouMonoVersion.Value; + + ulong uVersion = 0; + try + { + Type t = Type.GetType("Mono.Runtime"); + if(t != null) + { + MethodInfo mi = t.GetMethod("GetDisplayName", + BindingFlags.NonPublic | BindingFlags.Static); + if(mi != null) + { + string strName = (mi.Invoke(null, null) as string); + if(!string.IsNullOrEmpty(strName)) + { + Match m = Regex.Match(strName, "\\d+(\\.\\d+)+"); + if(m.Success) + uVersion = StrUtil.ParseVersion(m.Value); + else { Debug.Assert(false); } + } + else { Debug.Assert(false); } + } + else { Debug.Assert(false); } + } + } + catch(Exception) { Debug.Assert(false); } + + m_ouMonoVersion = uVersion; + return uVersion; + } + } + /// /// Determine if the native library is installed. /// @@ -91,15 +151,15 @@ namespace KeePassLib.Native { if(m_platID.HasValue) return m_platID.Value; -#if KeePassRT - m_platID = PlatformID.Win32NT; +#if KeePassUAP + m_platID = EnvironmentExt.OSVersion.Platform; #else m_platID = Environment.OSVersion.Platform; #endif -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) /*// Mono returns PlatformID.Unix on Mac OS X, workaround this - //fails on Anroid + //not supported on Mono if(m_platID.Value == PlatformID.Unix) { if((RunConsoleApp("uname", null) ?? string.Empty).Trim().Equals( @@ -111,7 +171,111 @@ namespace KeePassLib.Native return m_platID.Value; } + private static DesktopType? m_tDesktop = null; + public static DesktopType GetDesktopType() + { + if(!m_tDesktop.HasValue) + { + DesktopType t = DesktopType.None; + if(!IsUnix()) t = DesktopType.Windows; + else + { + try + { + string strXdg = (Environment.GetEnvironmentVariable( + "XDG_CURRENT_DESKTOP") ?? string.Empty).Trim(); + string strGdm = (Environment.GetEnvironmentVariable( + "GDMSESSION") ?? string.Empty).Trim(); + StringComparison sc = StrUtil.CaseIgnoreCmp; + if(strXdg.Equals("Unity", sc)) + t = DesktopType.Unity; + else if(strXdg.Equals("LXDE", sc)) + t = DesktopType.Lxde; + else if(strXdg.Equals("XFCE", sc)) + t = DesktopType.Xfce; + else if(strXdg.Equals("MATE", sc)) + t = DesktopType.Mate; + else if(strXdg.Equals("X-Cinnamon", sc)) + t = DesktopType.Cinnamon; + else if(strXdg.Equals("Pantheon", sc)) // Elementary OS + t = DesktopType.Pantheon; + else if(strXdg.Equals("KDE", sc) || // Mint 16 + strGdm.Equals("kde-plasma", sc)) // Ubuntu 12.04 + t = DesktopType.Kde; + else if(strXdg.Equals("GNOME", sc)) + { + if(strGdm.Equals("cinnamon", sc)) // Mint 13 + t = DesktopType.Cinnamon; + else t = DesktopType.Gnome; + } + } + catch(Exception) { Debug.Assert(false); } + } + + m_tDesktop = t; + } + + return m_tDesktop.Value; + } + +#if (!KeePassLibSD && !KeePassUAP) + /* Not supported on Android + public static string RunConsoleApp(string strAppPath, string strParams) + { + return RunConsoleApp(strAppPath, strParams, null); + } + public static string RunConsoleApp(string strAppPath, string strParams, + string strStdInput) + { + return RunConsoleApp(strAppPath, strParams, strStdInput, + (AppRunFlags.GetStdOutput | AppRunFlags.WaitForExit)); + } + */ + private delegate string RunProcessDelegate(); + + private static void EnsureNoBom(StreamWriter sw) + { + if(sw == null) { Debug.Assert(false); return; } + if(!MonoWorkarounds.IsRequired(1219)) return; + + try + { + Encoding enc = sw.Encoding; + if(enc == null) { Debug.Assert(false); return; } + byte[] pbBom = enc.GetPreamble(); + if((pbBom == null) || (pbBom.Length == 0)) return; + + // For Mono >= 4.0 (using Microsoft's reference source) + try + { + FieldInfo fi = typeof(StreamWriter).GetField("haveWrittenPreamble", + BindingFlags.Instance | BindingFlags.NonPublic); + if(fi != null) + { + fi.SetValue(sw, true); + return; + } + } + catch(Exception) { Debug.Assert(false); } + + // For Mono < 4.0 + FieldInfo fiPD = typeof(StreamWriter).GetField("preamble_done", + BindingFlags.Instance | BindingFlags.NonPublic); + if(fiPD != null) fiPD.SetValue(sw, true); + else { Debug.Assert(false); } + } + catch(Exception) { Debug.Assert(false); } + } +#endif + + /// + /// Transform a key. + /// + /// Source and destination buffer. + /// Key to use in the transformation. + /// Number of transformation rounds. + /// Returns true, if the key was transformed successfully. /// /// Transform a key. /// @@ -122,7 +286,7 @@ namespace KeePassLib.Native public static bool TransformKey256(byte[] pBuf256, byte[] pKey256, ulong uRounds) { - if(m_bAllowNative == false) return false; + if (m_bAllowNative == false) return false; try { @@ -136,10 +300,10 @@ namespace KeePassLib.Native return false; #endif } - catch(Exception e) + catch (Exception e) { Kp2aLog.Log(e.Message); - return false; + return false; } return true; @@ -148,19 +312,23 @@ namespace KeePassLib.Native /// /// Benchmark key transformation. /// - /// Number of seconds to perform the benchmark. + /// Number of milliseconds to perform the benchmark. /// Number of transformations done. /// Returns true, if the benchmark was successful. public static bool TransformKeyBenchmark256(uint uTimeMs, out ulong puRounds) { puRounds = 0; - if(m_bAllowNative == false) return false; +#if KeePassUAP + return false; +#else + if(!m_bAllowNative) return false; try { puRounds = NativeMethods.TransformKeyBenchmark(uTimeMs); } catch(Exception) { return false; } return true; +#endif } private static KeyValuePair PrepareArrays256(byte[] pBuf256, diff --git a/src/KeePassLib2Android/Native/NativeMethods.Unix.cs b/src/KeePassLib2Android/Native/NativeMethods.Unix.cs new file mode 100644 index 00000000..a03b3e29 --- /dev/null +++ b/src/KeePassLib2Android/Native/NativeMethods.Unix.cs @@ -0,0 +1,115 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; + +#if !KeePassUAP +using System.Windows.Forms; +#endif + +namespace KeePassLib.Native +{ + internal static partial class NativeMethods + { +#if (!KeePassLibSD && !KeePassUAP) + [StructLayout(LayoutKind.Sequential)] + private struct XClassHint + { + public IntPtr res_name; + public IntPtr res_class; + } + + [DllImport("libX11")] + private static extern int XSetClassHint(IntPtr display, IntPtr window, IntPtr class_hints); + + private static Type m_tXplatUIX11 = null; + private static Type GetXplatUIX11Type(bool bThrowOnError) + { + if(m_tXplatUIX11 == null) + { + // CheckState is in System.Windows.Forms + string strTypeCS = typeof(CheckState).AssemblyQualifiedName; + string strTypeX11 = strTypeCS.Replace("CheckState", "XplatUIX11"); + m_tXplatUIX11 = Type.GetType(strTypeX11, bThrowOnError, true); + } + + return m_tXplatUIX11; + } + + private static Type m_tHwnd = null; + private static Type GetHwndType(bool bThrowOnError) + { + if(m_tHwnd == null) + { + // CheckState is in System.Windows.Forms + string strTypeCS = typeof(CheckState).AssemblyQualifiedName; + string strTypeHwnd = strTypeCS.Replace("CheckState", "Hwnd"); + m_tHwnd = Type.GetType(strTypeHwnd, bThrowOnError, true); + } + + return m_tHwnd; + } + + internal static void SetWmClass(Form f, string strName, string strClass) + { + if(f == null) { Debug.Assert(false); return; } + + // The following crashes under Mac OS X (SIGSEGV in native code, + // not just an exception), thus skip it when we're on Mac OS X; + // https://sourceforge.net/projects/keepass/forums/forum/329221/topic/5860588 + if(NativeLib.GetPlatformID() == PlatformID.MacOSX) return; + + try + { + Type tXplatUIX11 = GetXplatUIX11Type(true); + FieldInfo fiDisplayHandle = tXplatUIX11.GetField("DisplayHandle", + BindingFlags.NonPublic | BindingFlags.Static); + IntPtr hDisplay = (IntPtr)fiDisplayHandle.GetValue(null); + + Type tHwnd = GetHwndType(true); + MethodInfo miObjectFromHandle = tHwnd.GetMethod("ObjectFromHandle", + BindingFlags.Public | BindingFlags.Static); + object oHwnd = miObjectFromHandle.Invoke(null, new object[] { f.Handle }); + + FieldInfo fiWholeWindow = tHwnd.GetField("whole_window", + BindingFlags.NonPublic | BindingFlags.Instance); + IntPtr hWindow = (IntPtr)fiWholeWindow.GetValue(oHwnd); + + XClassHint xch = new XClassHint(); + xch.res_name = Marshal.StringToCoTaskMemAnsi(strName ?? string.Empty); + xch.res_class = Marshal.StringToCoTaskMemAnsi(strClass ?? string.Empty); + IntPtr pXch = Marshal.AllocCoTaskMem(Marshal.SizeOf(xch)); + Marshal.StructureToPtr(xch, pXch, false); + + XSetClassHint(hDisplay, hWindow, pXch); + + Marshal.FreeCoTaskMem(pXch); + Marshal.FreeCoTaskMem(xch.res_name); + Marshal.FreeCoTaskMem(xch.res_class); + } + catch(Exception) { Debug.Assert(false); } + } +#endif + } +} diff --git a/src/KeePassLib2Android/Native/NativeMethods.cs b/src/KeePassLib2Android/Native/NativeMethods.cs index b8d6b041..07c47ab2 100644 --- a/src/KeePassLib2Android/Native/NativeMethods.cs +++ b/src/KeePassLib2Android/Native/NativeMethods.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,20 +18,22 @@ */ using System; -using System.Text; -using System.Security; -using System.Runtime.InteropServices; -using System.IO; using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; using KeePassLib.Utility; namespace KeePassLib.Native { - internal static class NativeMethods + internal static partial class NativeMethods { internal const int MAX_PATH = 260; + // internal const uint TF_SFT_SHOWNORMAL = 0x00000001; + // internal const uint TF_SFT_HIDDEN = 0x00000008; + /* [DllImport("KeePassNtv32.dll", EntryPoint = "TransformKey")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool TransformKey32(IntPtr pBuf256, @@ -70,6 +72,7 @@ namespace KeePassLib.Native return TransformKeyTimed32(pBuf256, pKey256, ref puRounds, uSeconds); } */ +#if !KeePassUAP [DllImport("KeePassLibC32.dll", EntryPoint = "TransformKey256")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool TransformKey32(IntPtr pBuf256, @@ -83,7 +86,7 @@ namespace KeePassLib.Native internal static bool TransformKey(IntPtr pBuf256, IntPtr pKey256, UInt64 uRounds) { - if(Marshal.SizeOf(typeof(IntPtr)) == 8) + if(NativeLib.PointerSize == 8) return TransformKey64(pBuf256, pKey256, uRounds); else return TransformKey32(pBuf256, pKey256, uRounds); @@ -97,69 +100,87 @@ namespace KeePassLib.Native internal static UInt64 TransformKeyBenchmark(UInt32 uTimeMs) { - if(Marshal.SizeOf(typeof(IntPtr)) == 8) + if(NativeLib.PointerSize == 8) return TransformKeyBenchmark64(uTimeMs); - else - return TransformKeyBenchmark32(uTimeMs); + return TransformKeyBenchmark32(uTimeMs); } +#endif -#if (!KeePassLibSD && !KeePassRT) - [DllImport("ShlWApi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] - internal static extern int StrCmpLogicalW(string x, string y); + /* [DllImport("KeePassLibC32.dll", EntryPoint = "TF_ShowLangBar")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool TF_ShowLangBar32(UInt32 dwFlags); + [DllImport("KeePassLibC64.dll", EntryPoint = "TF_ShowLangBar")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool TF_ShowLangBar64(UInt32 dwFlags); + + internal static bool TfShowLangBar(uint dwFlags) + { + if(Marshal.SizeOf(typeof(IntPtr)) == 8) + return TF_ShowLangBar64(dwFlags); + return TF_ShowLangBar32(dwFlags); + } */ + +#if (!KeePassLibSD && !KeePassUAP) [DllImport("ShlWApi.dll", CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool PathRelativePathTo([Out] StringBuilder pszPath, - [In] string pszFrom, [In] uint dwAttrFrom, [In] string pszTo, - [In] uint dwAttrTo); -#endif + [In] string pszFrom, uint dwAttrFrom, [In] string pszTo, uint dwAttrTo); - private static bool? m_bSupportsLogicalCmp = null; + [DllImport("ShlWApi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int StrCmpLogicalW(string x, string y); + + private static bool? m_obSupportsLogicalCmp = null; private static void TestNaturalComparisonsSupport() { -#if (KeePassLibSD || KeePassRT) -#warning No native natural comparisons supported. - m_bSupportsLogicalCmp = false; -#else try { StrCmpLogicalW("0", "0"); // Throws exception if unsupported - m_bSupportsLogicalCmp = true; + m_obSupportsLogicalCmp = true; } - catch(Exception) { m_bSupportsLogicalCmp = false; } -#endif + catch(Exception) { m_obSupportsLogicalCmp = false; } } +#endif internal static bool SupportsStrCmpNaturally { get { - if(m_bSupportsLogicalCmp.HasValue == false) +#if (!KeePassLibSD && !KeePassUAP) + if(!m_obSupportsLogicalCmp.HasValue) TestNaturalComparisonsSupport(); - return m_bSupportsLogicalCmp.Value; + return m_obSupportsLogicalCmp.Value; +#else + return false; +#endif } } internal static int StrCmpNaturally(string x, string y) { - if(m_bSupportsLogicalCmp.HasValue == false) TestNaturalComparisonsSupport(); - if(m_bSupportsLogicalCmp.Value == false) return 0; +#if (!KeePassLibSD && !KeePassUAP) + if(!NativeMethods.SupportsStrCmpNaturally) + { + Debug.Assert(false); + return string.Compare(x, y, true); + } -#if (KeePassLibSD || KeePassRT) -#warning No native natural comparisons supported. - return x.CompareTo(y); -#else return StrCmpLogicalW(x, y); +#else + Debug.Assert(false); + return string.Compare(x, y, true); #endif } internal static string GetUserRuntimeDir() { -#if !KeePassLibSD -#if KeePassRT - string strRtDir = Windows.Storage.ApplicationData.Current.LocalFolder.Path; +#if KeePassLibSD + return Path.GetTempPath(); +#else +#if KeePassUAP + string strRtDir = EnvironmentExt.AppDataLocalFolderPath; #else string strRtDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR"); if(string.IsNullOrEmpty(strRtDir)) @@ -175,8 +196,6 @@ namespace KeePassLib.Native strRtDir += PwDefs.ShortProductName; return strRtDir; -#else - return Path.GetTempPath(); #endif } } diff --git a/src/KeePassLib2Android/Properties/AssemblyInfo.cs b/src/KeePassLib2Android/Properties/AssemblyInfo.cs index 554155f1..48474729 100644 --- a/src/KeePassLib2Android/Properties/AssemblyInfo.cs +++ b/src/KeePassLib2Android/Properties/AssemblyInfo.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -27,7 +27,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dominik Reichl")] [assembly: AssemblyProduct("KeePassLib")] -[assembly: AssemblyCopyright("Copyright © 2003-2013 Dominik Reichl")] +[assembly: AssemblyCopyright("Copyright © 2003-2016 Dominik Reichl")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -38,5 +38,5 @@ using System.Runtime.InteropServices; [assembly: Guid("395f6eec-a1e0-4438-aa82-b75099348134")] // Assembly version information -[assembly: AssemblyVersion("2.24.0.*")] -[assembly: AssemblyFileVersion("2.24.0.0")] +[assembly: AssemblyVersion("2.34.0.*")] +[assembly: AssemblyFileVersion("2.34.0.0")] diff --git a/src/KeePassLib2Android/PwDatabase.cs b/src/KeePassLib2Android/PwDatabase.cs index 7c96cbbf..97eac76d 100644 --- a/src/KeePassLib2Android/PwDatabase.cs +++ b/src/KeePassLib2Android/PwDatabase.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -23,11 +21,15 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; + +#if !KeePassUAP using System.Drawing; +#endif using KeePassLib.Collections; using KeePassLib.Cryptography; using KeePassLib.Cryptography.Cipher; +using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Delegates; using KeePassLib.Interfaces; using KeePassLib.Keys; @@ -49,13 +51,14 @@ namespace KeePassLib private static bool m_bPrimaryCreated = false; - // Initializations see Clear() + // Initializations: see Clear() private PwGroup m_pgRootGroup = null; private PwObjectList m_vDeletedObjects = new PwObjectList(); private PwUuid m_uuidDataCipher = StandardAesEngine.AesUuid; private PwCompressionAlgorithm m_caCompression = PwCompressionAlgorithm.GZip; - private ulong m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; + // private ulong m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; + private KdfParameters m_kdfParams = KdfPool.GetDefaultParameters(); private CompositeKey m_pwUserKey = null; private MemoryProtectionConfig m_memProtConfig = new MemoryProtectionConfig(); @@ -63,6 +66,7 @@ namespace KeePassLib private List m_vCustomIcons = new List(); private bool m_bUINeedsIconUpdate = true; + private DateTime m_dtSettingsChanged = PwDefs.DtDefaultNow; private string m_strName = string.Empty; private DateTime m_dtNameChanged = PwDefs.DtDefaultNow; private string m_strDesc = string.Empty; @@ -92,7 +96,8 @@ namespace KeePassLib private int m_nHistoryMaxItems = DefaultHistoryMaxItems; private long m_lHistoryMaxSize = DefaultHistoryMaxSize; // In bytes - private StringDictionaryEx m_vCustomData = new StringDictionaryEx(); + private StringDictionaryEx m_dCustomData = new StringDictionaryEx(); + private VariantDictionary m_dPublicCustomData = new VariantDictionary(); private byte[] m_pbHashOfFileOnDisk = null; private byte[] m_pbHashOfLastIO = null; @@ -167,6 +172,12 @@ namespace KeePassLib } } + public DateTime SettingsChanged + { + get { return m_dtSettingsChanged; } + set { m_dtSettingsChanged = value; } + } + /// /// Name of the database. /// @@ -280,14 +291,23 @@ namespace KeePassLib set { m_caCompression = value; } } - /// - /// Number of key transformation rounds (in order to make dictionary - /// attacks harder). - /// - public ulong KeyEncryptionRounds + // /// + // /// Number of key transformation rounds (KDF parameter). + // /// + // public ulong KeyEncryptionRounds + // { + // get { return m_uKeyEncryptionRounds; } + // set { m_uKeyEncryptionRounds = value; } + // } + + public KdfParameters KdfParameters { - get { return m_uKeyEncryptionRounds; } - set { m_uKeyEncryptionRounds = value; } + get { return m_kdfParams; } + set + { + if(value == null) throw new ArgumentNullException("value"); + m_kdfParams = value; + } } /// @@ -407,14 +427,37 @@ namespace KeePassLib /// /// Custom data container that can be used by plugins to store /// own data in KeePass databases. + /// The data is stored in the encrypted part of encrypted + /// database files. + /// Use unique names for your items, e.g. "PluginName_ItemName". /// public StringDictionaryEx CustomData { - get { return m_vCustomData; } - set + get { return m_dCustomData; } + internal set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); - m_vCustomData = value; + if(value == null) { Debug.Assert(false); throw new ArgumentNullException("value"); } + m_dCustomData = value; + } + } + + /// + /// Custom data container that can be used by plugins to store + /// own data in KeePass databases. + /// The data is stored in the *unencrypted* part of database files, + /// and it is not supported by all file formats (e.g. supported by KDBX, + /// unsupported by XML). + /// It is highly recommended to use CustomData instead, + /// if possible. + /// Use unique names for your items, e.g. "PluginName_ItemName". + /// + public VariantDictionary PublicCustomData + { + get { return m_dPublicCustomData; } + internal set + { + if(value == null) { Debug.Assert(false); throw new ArgumentNullException("value"); } + m_dPublicCustomData = value; } } @@ -485,7 +528,8 @@ namespace KeePassLib m_uuidDataCipher = StandardAesEngine.AesUuid; m_caCompression = PwCompressionAlgorithm.GZip; - m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; + // m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds; + m_kdfParams = KdfPool.GetDefaultParameters(); m_pwUserKey = null; m_memProtConfig = new MemoryProtectionConfig(); @@ -495,6 +539,7 @@ namespace KeePassLib DateTime dtNow = DateTime.Now; + m_dtSettingsChanged = dtNow; m_strName = string.Empty; m_dtNameChanged = dtNow; m_strDesc = string.Empty; @@ -524,7 +569,8 @@ namespace KeePassLib m_nHistoryMaxItems = DefaultHistoryMaxItems; m_lHistoryMaxSize = DefaultHistoryMaxSize; - m_vCustomData = new StringDictionaryEx(); + m_dCustomData = new StringDictionaryEx(); + m_dPublicCustomData = new VariantDictionary(); m_pbHashOfFileOnDisk = null; m_pbHashOfLastIO = null; @@ -564,20 +610,23 @@ namespace KeePassLib /// Open a database. The URL may point to any supported data source. /// /// IO connection to load the database from. - /// sKey used to open the specified database. + /// Key used to open the specified database. /// Logger, which gets all status messages. - /// public void Open(IOConnectionInfo ioSource, CompositeKey pwKey, IStatusLogger slLogger, IDatabaseFormat format) + { - Open(IOConnection.OpenRead(ioSource), UrlUtil.StripExtension( - UrlUtil.GetFileName(ioSource.Path)), ioSource, pwKey, slLogger , format); - + Open(IOConnection.OpenRead(ioSource), UrlUtil.StripExtension( + UrlUtil.GetFileName(ioSource.Path)), ioSource, pwKey, slLogger, format); + } /// - /// Open a database provided as Stream. + /// Open a database. The URL may point to any supported data source. /// + /// IO connection to load the database from. + /// Key used to open the specified database. + /// Logger, which gets all status messages. public void Open(Stream s, string fileNameWithoutPathAndExt, IOConnectionInfo ioSource, CompositeKey pwKey, IStatusLogger slLogger, IDatabaseFormat format) { @@ -587,9 +636,9 @@ namespace KeePassLib if (fileNameWithoutPathAndExt == null) throw new ArgumentException("fileNameWithoutPathAndExt"); Debug.Assert(pwKey != null); Debug.Assert(ioSource != null); - if (ioSource == null) throw new ArgumentNullException("ioSource"); - - if (pwKey == null) throw new ArgumentNullException("pwKey"); + if(ioSource == null) throw new ArgumentNullException("ioSource"); + Debug.Assert(pwKey != null); + if(pwKey == null) throw new ArgumentNullException("pwKey"); Close(); @@ -603,22 +652,22 @@ namespace KeePassLib m_bModified = false; format.PopulateDatabaseFromStream(this, s, slLogger); - + m_pbHashOfLastIO = format.HashOfLastStream; - m_pbHashOfFileOnDisk = format.HashOfLastStream; + m_pbHashOfFileOnDisk = format.HashOfLastStream; + Debug.Assert(m_pbHashOfFileOnDisk != null); m_bDatabaseOpened = true; m_ioSource = ioSource; } - catch (Exception) + catch(Exception) { Clear(); throw; } } - /// /// Save the currently opened database. The file is written to the location /// it has been opened from. @@ -626,7 +675,7 @@ namespace KeePassLib /// Logger that recieves status information. public void Save(IStatusLogger slLogger) { - Debug.Assert(ValidateUuidUniqueness()); + Debug.Assert(!HasDuplicateUuids()); FileLock fl = null; if(m_bUseFileLocks) fl = new FileLock(m_ioSource); @@ -640,7 +689,7 @@ namespace KeePassLib kdb.Save(s, null, KdbpFile.GetFormatToUse(m_ioSource), slLogger); ft.CommitWrite(); - + m_pbHashOfLastIO = kdb.HashOfFileOnDisk; m_pbHashOfFileOnDisk = kdb.HashOfFileOnDisk; Debug.Assert(m_pbHashOfFileOnDisk != null); @@ -656,10 +705,9 @@ namespace KeePassLib /// This allows to save to cloud locations etc. public void Save(Stream streamOfOriginalLocation, IStatusLogger slLogger) { - Debug.Assert(ValidateUuidUniqueness()); Stream s = streamOfOriginalLocation; KdbxFile kdb = new KdbxFile(this); - kdb.Save(s, null, KdbpFile.GetFormatToUse(m_ioSource), slLogger); + kdb.Save(s, null, KdbxFormat.Default, slLogger); m_pbHashOfLastIO = kdb.HashOfFileOnDisk; m_pbHashOfFileOnDisk = kdb.HashOfFileOnDisk; @@ -717,43 +765,53 @@ namespace KeePassLib Clear(); } - public void MergeIn(PwDatabase pwSource, PwMergeMethod mm) + public void MergeIn(PwDatabase pdSource, PwMergeMethod mm) { - MergeIn(pwSource, mm, null); + MergeIn(pdSource, mm, null); } - /// - /// Synchronize the current database with another one. - /// - /// Input database to synchronize with. This input - /// database is used to update the current one, but is not modified! You - /// must copy the current object if you want a second instance of the - /// synchronized database. The input database must not be seen as valid - /// database any more after calling Synchronize. - /// Merge method. - /// Logger to report status messages to. - /// May be null. - public void MergeIn(PwDatabase pwSource, PwMergeMethod mm, + public void MergeIn(PwDatabase pdSource, PwMergeMethod mm, IStatusLogger slStatus) { - if(pwSource == null) throw new ArgumentNullException("pwSource"); - - PwGroup pgOrgStructure = m_pgRootGroup.CloneStructure(); - PwGroup pgSrcStructure = pwSource.m_pgRootGroup.CloneStructure(); + if(pdSource == null) throw new ArgumentNullException("pdSource"); if(mm == PwMergeMethod.CreateNewUuids) - pwSource.RootGroup.CreateNewItemUuids(true, true, true); - - GroupHandler gh = delegate(PwGroup pg) { - if(pg == pwSource.m_pgRootGroup) return true; + pdSource.RootGroup.Uuid = new PwUuid(true); + pdSource.RootGroup.CreateNewItemUuids(true, true, true); + } + // PwGroup pgOrgStructure = m_pgRootGroup.CloneStructure(); + // PwGroup pgSrcStructure = pdSource.RootGroup.CloneStructure(); + // Later in case 'if(mm == PwMergeMethod.Synchronize)': + // PwObjectPoolEx ppOrg = PwObjectPoolEx.FromGroup(pgOrgStructure); + // PwObjectPoolEx ppSrc = PwObjectPoolEx.FromGroup(pgSrcStructure); + + PwObjectPoolEx ppOrg = PwObjectPoolEx.FromGroup(m_pgRootGroup); + PwObjectPoolEx ppSrc = PwObjectPoolEx.FromGroup(pdSource.RootGroup); + + GroupHandler ghSrc = delegate(PwGroup pg) + { + // if(pg == pdSource.m_pgRootGroup) return true; + + // Do not use ppOrg for finding the group, because new groups + // might have been added (which are not in the pool, and the + // pool should not be modified) PwGroup pgLocal = m_pgRootGroup.FindGroup(pg.Uuid, true); + if(pgLocal == null) { PwGroup pgSourceParent = pg.ParentGroup; PwGroup pgLocalContainer; - if(pgSourceParent == pwSource.m_pgRootGroup) + if(pgSourceParent == null) + { + // pg is the root group of pdSource, and no corresponding + // local group was found; create the group within the + // local root group + Debug.Assert(pg == pdSource.m_pgRootGroup); + pgLocalContainer = m_pgRootGroup; + } + else if(pgSourceParent == pdSource.m_pgRootGroup) pgLocalContainer = m_pgRootGroup; else pgLocalContainer = m_pgRootGroup.FindGroup(pgSourceParent.Uuid, true); @@ -763,7 +821,10 @@ namespace KeePassLib PwGroup pgNew = new PwGroup(false, false); pgNew.Uuid = pg.Uuid; pgNew.AssignProperties(pg, false, true); - pgLocalContainer.AddGroup(pgNew, true); + + // pgLocalContainer.AddGroup(pgNew, true); + InsertObjectAtBestPos(pgLocalContainer.Groups, pgNew, ppSrc); + pgNew.ParentGroup = pgLocalContainer; } else // pgLocal != null { @@ -782,14 +843,18 @@ namespace KeePassLib return ((slStatus != null) ? slStatus.ContinueWork() : true); }; - EntryHandler eh = delegate(PwEntry pe) + EntryHandler ehSrc = delegate(PwEntry pe) { - PwEntry peLocal = m_pgRootGroup.FindEntry(pe.Uuid, true); + // PwEntry peLocal = m_pgRootGroup.FindEntry(pe.Uuid, true); + PwEntry peLocal = (ppOrg.GetItemByUuid(pe.Uuid) as PwEntry); + Debug.Assert(object.ReferenceEquals(peLocal, + m_pgRootGroup.FindEntry(pe.Uuid, true))); + if(peLocal == null) { PwGroup pgSourceParent = pe.ParentGroup; PwGroup pgLocalContainer; - if(pgSourceParent == pwSource.m_pgRootGroup) + if(pgSourceParent == pdSource.m_pgRootGroup) pgLocalContainer = m_pgRootGroup; else pgLocalContainer = m_pgRootGroup.FindGroup(pgSourceParent.Uuid, true); @@ -799,7 +864,10 @@ namespace KeePassLib PwEntry peNew = new PwEntry(false, false); peNew.Uuid = pe.Uuid; peNew.AssignProperties(pe, false, true, true); - pgLocalContainer.AddEntry(peNew, true); + + // pgLocalContainer.AddEntry(peNew, true); + InsertObjectAtBestPos(pgLocalContainer.Entries, peNew, ppSrc); + peNew.ParentGroup = pgLocalContainer; } else // peLocal != null { @@ -836,7 +904,8 @@ namespace KeePassLib return ((slStatus != null) ? slStatus.ContinueWork() : true); }; - if(!pwSource.RootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh)) + ghSrc(pdSource.RootGroup); + if(!pdSource.RootGroup.TraverseTree(TraversalMethod.PreOrder, ghSrc, ehSrc)) throw new InvalidOperationException(); IStatusLogger slPrevStatus = m_slStatus; @@ -844,39 +913,42 @@ namespace KeePassLib if(mm == PwMergeMethod.Synchronize) { - ApplyDeletions(pwSource.m_vDeletedObjects, true); - ApplyDeletions(m_vDeletedObjects, false); + RelocateGroups(ppOrg, ppSrc); + RelocateEntries(ppOrg, ppSrc); + ReorderObjects(m_pgRootGroup, ppOrg, ppSrc); - PwObjectPool ppOrgGroups = PwObjectPool.FromGroupRecursive( - pgOrgStructure, false); - PwObjectPool ppSrcGroups = PwObjectPool.FromGroupRecursive( - pgSrcStructure, false); - PwObjectPool ppOrgEntries = PwObjectPool.FromGroupRecursive( - pgOrgStructure, true); - PwObjectPool ppSrcEntries = PwObjectPool.FromGroupRecursive( - pgSrcStructure, true); + // After all relocations and reorderings + MergeInLocationChanged(m_pgRootGroup, ppOrg, ppSrc); + ppOrg = null; // Pools are now invalid, because the location + ppSrc = null; // changed times have been merged in - RelocateGroups(ppOrgGroups, ppSrcGroups); - ReorderGroups(ppOrgGroups, ppSrcGroups); - RelocateEntries(ppOrgEntries, ppSrcEntries); - ReorderEntries(ppOrgEntries, ppSrcEntries); - Debug.Assert(ValidateUuidUniqueness()); + // Delete *after* relocating, because relocating might + // empty some groups that are marked for deletion (and + // objects that weren't relocated yet might prevent the + // deletion) + Dictionary dOrgDel = CreateDeletedObjectsPool(); + MergeInDeletionInfo(pdSource.m_vDeletedObjects, dOrgDel); + ApplyDeletions(m_pgRootGroup, dOrgDel); + + // The list and the dictionary should be kept in sync + Debug.Assert(m_vDeletedObjects.UCount == (uint)dOrgDel.Count); } // Must be called *after* merging groups, because group UUIDs // are required for recycle bin and entry template UUIDs - MergeInDbProperties(pwSource, mm); + MergeInDbProperties(pdSource, mm); - MergeInCustomIcons(pwSource); + MergeInCustomIcons(pdSource); MaintainBackups(); + Debug.Assert(!HasDuplicateUuids()); m_slStatus = slPrevStatus; } - private void MergeInCustomIcons(PwDatabase pwSource) + private void MergeInCustomIcons(PwDatabase pdSource) { - foreach(PwCustomIcon pwci in pwSource.CustomIcons) + foreach(PwCustomIcon pwci in pdSource.CustomIcons) { if(GetCustomIconIndex(pwci.Uuid) >= 0) continue; @@ -885,83 +957,120 @@ namespace KeePassLib } } - /// - /// Apply a list of deleted objects. - /// - /// List of deleted objects. - private void ApplyDeletions(PwObjectList listDelObjects, - bool bCopyDeletionInfoToLocal) + private Dictionary CreateDeletedObjectsPool() { - Debug.Assert(listDelObjects != null); if(listDelObjects == null) throw new ArgumentNullException("listDelObjects"); + Dictionary d = + new Dictionary(); - LinkedList listGroupsToDelete = new LinkedList(); - LinkedList listEntriesToDelete = new LinkedList(); - - GroupHandler gh = delegate(PwGroup pg) + int n = (int)m_vDeletedObjects.UCount; + for(int i = n - 1; i >= 0; --i) { - if(pg == m_pgRootGroup) return true; + PwDeletedObject pdo = m_vDeletedObjects.GetAt((uint)i); - foreach(PwDeletedObject pdo in listDelObjects) + PwDeletedObject pdoEx; + if(d.TryGetValue(pdo.Uuid, out pdoEx)) { - if(pg.Uuid.Equals(pdo.Uuid)) - { - if(TimeUtil.Compare(pg.LastModificationTime, - pdo.DeletionTime, true) < 0) - listGroupsToDelete.AddLast(pg); - } + Debug.Assert(false); // Found duplicate, which should not happen + + if(pdo.DeletionTime > pdoEx.DeletionTime) + pdoEx.DeletionTime = pdo.DeletionTime; + + m_vDeletedObjects.RemoveAt((uint)i); } + else d[pdo.Uuid] = pdo; + } - return ((m_slStatus != null) ? m_slStatus.ContinueWork() : true); - }; + return d; + } - EntryHandler eh = delegate(PwEntry pe) + private void MergeInDeletionInfo(PwObjectList lSrc, + Dictionary dOrgDel) + { + foreach(PwDeletedObject pdoSrc in lSrc) { - foreach(PwDeletedObject pdo in listDelObjects) + PwDeletedObject pdoOrg; + if(dOrgDel.TryGetValue(pdoSrc.Uuid, out pdoOrg)) // Update { - if(pe.Uuid.Equals(pdo.Uuid)) - { - if(TimeUtil.Compare(pe.LastModificationTime, - pdo.DeletionTime, true) < 0) - listEntriesToDelete.AddLast(pe); - } + Debug.Assert(pdoOrg.Uuid.Equals(pdoSrc.Uuid)); + + if(pdoSrc.DeletionTime > pdoOrg.DeletionTime) + pdoOrg.DeletionTime = pdoSrc.DeletionTime; } - - return ((m_slStatus != null) ? m_slStatus.ContinueWork() : true); - }; - - m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh); - - foreach(PwGroup pg in listGroupsToDelete) - pg.ParentGroup.Groups.Remove(pg); - foreach(PwEntry pe in listEntriesToDelete) - pe.ParentGroup.Entries.Remove(pe); - - if(bCopyDeletionInfoToLocal) - { - foreach(PwDeletedObject pdoNew in listDelObjects) + else // Add { - bool bCopy = true; - - foreach(PwDeletedObject pdoLocal in m_vDeletedObjects) - { - if(pdoNew.Uuid.Equals(pdoLocal.Uuid)) - { - bCopy = false; - - if(pdoNew.DeletionTime > pdoLocal.DeletionTime) - pdoLocal.DeletionTime = pdoNew.DeletionTime; - - break; - } - } - - if(bCopy) m_vDeletedObjects.Add(pdoNew); + m_vDeletedObjects.Add(pdoSrc); + dOrgDel[pdoSrc.Uuid] = pdoSrc; } } } - private void RelocateGroups(PwObjectPool ppOrgStructure, - PwObjectPool ppSrcStructure) + private void ApplyDeletions(PwObjectList l, Predicate fCanDelete, + Dictionary dOrgDel) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable + { + int n = (int)l.UCount; + for(int i = n - 1; i >= 0; --i) + { + if((m_slStatus != null) && !m_slStatus.ContinueWork()) break; + + T t = l.GetAt((uint)i); + + PwDeletedObject pdo; + if(dOrgDel.TryGetValue(t.Uuid, out pdo)) + { + Debug.Assert(t.Uuid.Equals(pdo.Uuid)); + + bool bDel = (TimeUtil.Compare(t.LastModificationTime, + pdo.DeletionTime, true) < 0); + bDel &= fCanDelete(t); + + if(bDel) l.RemoveAt((uint)i); + else + { + // Prevent future deletion attempts; this also prevents + // delayed deletions (emptying a group could cause a + // group to be deleted, if the deletion was prevented + // before due to the group not being empty) + if(!m_vDeletedObjects.Remove(pdo)) { Debug.Assert(false); } + if(!dOrgDel.Remove(pdo.Uuid)) { Debug.Assert(false); } + } + } + } + } + + private static bool SafeCanDeleteGroup(PwGroup pg) + { + if(pg == null) { Debug.Assert(false); return false; } + + if(pg.Groups.UCount > 0) return false; + if(pg.Entries.UCount > 0) return false; + return true; + } + + private static bool SafeCanDeleteEntry(PwEntry pe) + { + if(pe == null) { Debug.Assert(false); return false; } + + return true; + } + + // Apply deletions on all objects in the specified container + // (but not the container itself), using post-order traversal + // to avoid implicit deletions; + // https://sourceforge.net/p/keepass/bugs/1499/ + private void ApplyDeletions(PwGroup pgContainer, + Dictionary dOrgDel) + { + foreach(PwGroup pg in pgContainer.Groups) // Post-order traversal + { + ApplyDeletions(pg, dOrgDel); + } + + ApplyDeletions(pgContainer.Groups, PwDatabase.SafeCanDeleteGroup, dOrgDel); + ApplyDeletions(pgContainer.Entries, PwDatabase.SafeCanDeleteEntry, dOrgDel); + } + + private void RelocateGroups(PwObjectPoolEx ppOrg, PwObjectPoolEx ppSrc) { PwObjectList vGroups = m_pgRootGroup.GetGroups(true); @@ -970,18 +1079,25 @@ namespace KeePassLib if((m_slStatus != null) && !m_slStatus.ContinueWork()) break; // PwGroup pgOrg = pgOrgStructure.FindGroup(pg.Uuid, true); - IStructureItem ptOrg = ppOrgStructure.Get(pg.Uuid); + IStructureItem ptOrg = ppOrg.GetItemByUuid(pg.Uuid); if(ptOrg == null) continue; // PwGroup pgSrc = pgSrcStructure.FindGroup(pg.Uuid, true); - IStructureItem ptSrc = ppSrcStructure.Get(pg.Uuid); + IStructureItem ptSrc = ppSrc.GetItemByUuid(pg.Uuid); if(ptSrc == null) continue; PwGroup pgOrgParent = ptOrg.ParentGroup; + // vGroups does not contain the root group, thus pgOrgParent + // should not be null + if(pgOrgParent == null) { Debug.Assert(false); continue; } + PwGroup pgSrcParent = ptSrc.ParentGroup; + // pgSrcParent may be null (for the source root group) + if(pgSrcParent == null) continue; + if(pgOrgParent.Uuid.Equals(pgSrcParent.Uuid)) { - pg.LocationChanged = ((ptSrc.LocationChanged > ptOrg.LocationChanged) ? - ptSrc.LocationChanged : ptOrg.LocationChanged); + // pg.LocationChanged = ((ptSrc.LocationChanged > ptOrg.LocationChanged) ? + // ptSrc.LocationChanged : ptOrg.LocationChanged); continue; } @@ -993,8 +1109,12 @@ namespace KeePassLib if(pgLocal.IsContainedIn(pg)) continue; pg.ParentGroup.Groups.Remove(pg); - pgLocal.AddGroup(pg, true); - pg.LocationChanged = ptSrc.LocationChanged; + + // pgLocal.AddGroup(pg, true); + InsertObjectAtBestPos(pgLocal.Groups, pg, ppSrc); + pg.ParentGroup = pgLocal; + + // pg.LocationChanged = ptSrc.LocationChanged; } else { @@ -1006,8 +1126,7 @@ namespace KeePassLib Debug.Assert(m_pgRootGroup.GetGroups(true).UCount == vGroups.UCount); } - private void RelocateEntries(PwObjectPool ppOrgStructure, - PwObjectPool ppSrcStructure) + private void RelocateEntries(PwObjectPoolEx ppOrg, PwObjectPoolEx ppSrc) { PwObjectList vEntries = m_pgRootGroup.GetEntries(true); @@ -1016,18 +1135,18 @@ namespace KeePassLib if((m_slStatus != null) && !m_slStatus.ContinueWork()) break; // PwEntry peOrg = pgOrgStructure.FindEntry(pe.Uuid, true); - IStructureItem ptOrg = ppOrgStructure.Get(pe.Uuid); + IStructureItem ptOrg = ppOrg.GetItemByUuid(pe.Uuid); if(ptOrg == null) continue; // PwEntry peSrc = pgSrcStructure.FindEntry(pe.Uuid, true); - IStructureItem ptSrc = ppSrcStructure.Get(pe.Uuid); + IStructureItem ptSrc = ppSrc.GetItemByUuid(pe.Uuid); if(ptSrc == null) continue; PwGroup pgOrg = ptOrg.ParentGroup; PwGroup pgSrc = ptSrc.ParentGroup; if(pgOrg.Uuid.Equals(pgSrc.Uuid)) { - pe.LocationChanged = ((ptSrc.LocationChanged > ptOrg.LocationChanged) ? - ptSrc.LocationChanged : ptOrg.LocationChanged); + // pe.LocationChanged = ((ptSrc.LocationChanged > ptOrg.LocationChanged) ? + // ptSrc.LocationChanged : ptOrg.LocationChanged); continue; } @@ -1037,8 +1156,12 @@ namespace KeePassLib if(pgLocal == null) { Debug.Assert(false); continue; } pe.ParentGroup.Entries.Remove(pe); - pgLocal.AddEntry(pe, true); - pe.LocationChanged = ptSrc.LocationChanged; + + // pgLocal.AddEntry(pe, true); + InsertObjectAtBestPos(pgLocal.Entries, pe, ppSrc); + pe.ParentGroup = pgLocal; + + // pe.LocationChanged = ptSrc.LocationChanged; } else { @@ -1050,274 +1173,338 @@ namespace KeePassLib Debug.Assert(m_pgRootGroup.GetEntries(true).UCount == vEntries.UCount); } - private void ReorderGroups(PwObjectPool ppOrgStructure, - PwObjectPool ppSrcStructure) + private void ReorderObjects(PwGroup pg, PwObjectPoolEx ppOrg, + PwObjectPoolEx ppSrc) { - GroupHandler gh = delegate(PwGroup pg) - { - ReorderObjectList(pg.Groups, ppOrgStructure, - ppSrcStructure, false); - return true; - }; + ReorderObjectList(pg.Groups, ppOrg, ppSrc); + ReorderObjectList(pg.Entries, ppOrg, ppSrc); - ReorderObjectList(m_pgRootGroup.Groups, ppOrgStructure, - ppSrcStructure, false); - m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, null); + foreach(PwGroup pgSub in pg.Groups) + { + ReorderObjects(pgSub, ppOrg, ppSrc); + } } - private void ReorderEntries(PwObjectPool ppOrgStructure, - PwObjectPool ppSrcStructure) + private void ReorderObjectList(PwObjectList lItems, + PwObjectPoolEx ppOrg, PwObjectPoolEx ppSrc) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable { - GroupHandler gh = delegate(PwGroup pg) - { - ReorderObjectList(pg.Entries, ppOrgStructure, - ppSrcStructure, true); - return true; - }; - - ReorderObjectList(m_pgRootGroup.Entries, ppOrgStructure, - ppSrcStructure, true); - m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, null); - } - - private void ReorderObjectList(PwObjectList vItems, - PwObjectPool ppOrgStructure, PwObjectPool ppSrcStructure, bool bEntries) - where T : class, IStructureItem, IDeepCloneable - { - if(!ObjectListRequiresReorder(vItems, ppOrgStructure, ppSrcStructure, - bEntries)) return; + List> lBlocks = PartitionConsec(lItems, ppOrg, ppSrc); + if(lBlocks.Count <= 1) return; #if DEBUG - PwObjectList vOrgListItems = vItems.CloneShallow(); + PwObjectList lOrgItems = lItems.CloneShallow(); #endif - Queue> qToDo = new Queue>(); - qToDo.Enqueue(new KeyValuePair(0, vItems.UCount - 1)); + Queue> qToDo = new Queue>(); + qToDo.Enqueue(new KeyValuePair(0, lBlocks.Count - 1)); while(qToDo.Count > 0) { if((m_slStatus != null) && !m_slStatus.ContinueWork()) break; - KeyValuePair kvp = qToDo.Dequeue(); - if(kvp.Value <= kvp.Key) { Debug.Assert(false); continue; } + KeyValuePair kvp = qToDo.Dequeue(); + if(kvp.Key >= kvp.Value) { Debug.Assert(false); continue; } - Queue qRelBefore = new Queue(); - Queue qRelAfter = new Queue(); - uint uPivot = FindLocationChangedPivot(vItems, kvp, ppOrgStructure, - ppSrcStructure, qRelBefore, qRelAfter, bEntries); - T ptPivot = vItems.GetAt(uPivot); + PwObjectPoolEx pPool; + int iPivot = FindLocationChangedPivot(lBlocks, kvp, out pPool); + PwObjectBlock bPivot = lBlocks[iPivot]; - List vToSort = vItems.GetRange(kvp.Key, kvp.Value); - Queue qBefore = new Queue(); - Queue qAfter = new Queue(); + T tPivotPrimary = bPivot.PrimaryItem; + if(tPivotPrimary == null) { Debug.Assert(false); continue; } + ulong idPivot = pPool.GetIdByUuid(tPivotPrimary.Uuid); + if(idPivot == 0) { Debug.Assert(false); continue; } + + Queue> qBefore = new Queue>(); + Queue> qAfter = new Queue>(); bool bBefore = true; - foreach(T pt in vToSort) + for(int i = kvp.Key; i <= kvp.Value; ++i) { - if(pt == ptPivot) { bBefore = false; continue; } + if(i == iPivot) { bBefore = false; continue; } - bool bAdded = false; - foreach(PwUuid puBefore in qRelBefore) + PwObjectBlock b = lBlocks[i]; + Debug.Assert(b.LocationChanged <= bPivot.LocationChanged); + + T t = b.PrimaryItem; + if(t != null) { - if(puBefore.Equals(pt.Uuid)) + ulong idBPri = pPool.GetIdByUuid(t.Uuid); + if(idBPri > 0) { - qBefore.Enqueue(pt); - bAdded = true; - break; + if(idBPri < idPivot) qBefore.Enqueue(b); + else qAfter.Enqueue(b); + + continue; } } - if(bAdded) continue; + else { Debug.Assert(false); } - foreach(PwUuid puAfter in qRelAfter) - { - if(puAfter.Equals(pt.Uuid)) - { - qAfter.Enqueue(pt); - bAdded = true; - break; - } - } - if(bAdded) continue; - - if(bBefore) qBefore.Enqueue(pt); - else qAfter.Enqueue(pt); - } - Debug.Assert(bBefore == false); - - uint uPos = kvp.Key; - while(qBefore.Count > 0) vItems.SetAt(uPos++, qBefore.Dequeue()); - vItems.SetAt(uPos++, ptPivot); - while(qAfter.Count > 0) vItems.SetAt(uPos++, qAfter.Dequeue()); - Debug.Assert(uPos == (kvp.Value + 1)); - - int iNewPivot = vItems.IndexOf(ptPivot); - if((iNewPivot < (int)kvp.Key) || (iNewPivot > (int)kvp.Value)) - { - Debug.Assert(false); - continue; + if(bBefore) qBefore.Enqueue(b); + else qAfter.Enqueue(b); } - if((iNewPivot - 1) > (int)kvp.Key) - qToDo.Enqueue(new KeyValuePair(kvp.Key, - (uint)(iNewPivot - 1))); + int j = kvp.Key; + while(qBefore.Count > 0) { lBlocks[j] = qBefore.Dequeue(); ++j; } + int iNewPivot = j; + lBlocks[j] = bPivot; + ++j; + while(qAfter.Count > 0) { lBlocks[j] = qAfter.Dequeue(); ++j; } + Debug.Assert(j == (kvp.Value + 1)); - if((iNewPivot + 1) < (int)kvp.Value) - qToDo.Enqueue(new KeyValuePair((uint)(iNewPivot + 1), - kvp.Value)); + if((iNewPivot - 1) > kvp.Key) + qToDo.Enqueue(new KeyValuePair(kvp.Key, iNewPivot - 1)); + if((iNewPivot + 1) < kvp.Value) + qToDo.Enqueue(new KeyValuePair(iNewPivot + 1, kvp.Value)); } -#if DEBUG - foreach(T ptItem in vOrgListItems) + uint u = 0; + foreach(PwObjectBlock b in lBlocks) { - Debug.Assert(vItems.IndexOf(ptItem) >= 0); + foreach(T t in b) + { + lItems.SetAt(u, t); + ++u; + } + } + Debug.Assert(u == lItems.UCount); + +#if DEBUG + Debug.Assert(u == lOrgItems.UCount); + foreach(T ptItem in lOrgItems) + { + Debug.Assert(lItems.IndexOf(ptItem) >= 0); } #endif } - private static uint FindLocationChangedPivot(PwObjectList vItems, - KeyValuePair kvpRange, PwObjectPool ppOrgStructure, - PwObjectPool ppSrcStructure, Queue qBefore, Queue qAfter, - bool bEntries) - where T : class, IStructureItem, IDeepCloneable + private static List> PartitionConsec(PwObjectList lItems, + PwObjectPoolEx ppOrg, PwObjectPoolEx ppSrc) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable { - uint uPosMax = kvpRange.Key; + List> lBlocks = new List>(); + + Dictionary dItemUuids = new Dictionary(); + foreach(T t in lItems) { dItemUuids[t.Uuid] = true; } + + uint n = lItems.UCount; + for(uint u = 0; u < n; ++u) + { + T t = lItems.GetAt(u); + + PwObjectBlock b = new PwObjectBlock(); + + DateTime dtLoc; + PwObjectPoolEx pPool = GetBestPool(t, ppOrg, ppSrc, out dtLoc); + b.Add(t, dtLoc, pPool); + + lBlocks.Add(b); + + ulong idOrg = ppOrg.GetIdByUuid(t.Uuid); + ulong idSrc = ppSrc.GetIdByUuid(t.Uuid); + if((idOrg == 0) || (idSrc == 0)) continue; + + for(uint x = u + 1; x < n; ++x) + { + T tNext = lItems.GetAt(x); + + ulong idOrgNext = idOrg + 1; + while(true) + { + IStructureItem ptOrg = ppOrg.GetItemById(idOrgNext); + if(ptOrg == null) { idOrgNext = 0; break; } + if(ptOrg.Uuid.Equals(tNext.Uuid)) break; // Found it + if(dItemUuids.ContainsKey(ptOrg.Uuid)) { idOrgNext = 0; break; } + ++idOrgNext; + } + if(idOrgNext == 0) break; + + ulong idSrcNext = idSrc + 1; + while(true) + { + IStructureItem ptSrc = ppSrc.GetItemById(idSrcNext); + if(ptSrc == null) { idSrcNext = 0; break; } + if(ptSrc.Uuid.Equals(tNext.Uuid)) break; // Found it + if(dItemUuids.ContainsKey(ptSrc.Uuid)) { idSrcNext = 0; break; } + ++idSrcNext; + } + if(idSrcNext == 0) break; + + pPool = GetBestPool(tNext, ppOrg, ppSrc, out dtLoc); + b.Add(tNext, dtLoc, pPool); + + ++u; + idOrg = idOrgNext; + idSrc = idSrcNext; + } + } + + return lBlocks; + } + + private static PwObjectPoolEx GetBestPool(T t, PwObjectPoolEx ppOrg, + PwObjectPoolEx ppSrc, out DateTime dtLoc) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable + { + PwObjectPoolEx p = null; + dtLoc = DateTime.MinValue; + + IStructureItem ptOrg = ppOrg.GetItemByUuid(t.Uuid); + if(ptOrg != null) + { + dtLoc = ptOrg.LocationChanged; + p = ppOrg; + } + + IStructureItem ptSrc = ppSrc.GetItemByUuid(t.Uuid); + if((ptSrc != null) && (ptSrc.LocationChanged > dtLoc)) + { + dtLoc = ptSrc.LocationChanged; + p = ppSrc; + } + + Debug.Assert(p != null); + return p; + } + + private static int FindLocationChangedPivot(List> lBlocks, + KeyValuePair kvpRange, out PwObjectPoolEx pPool) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable + { + pPool = null; + + int iPosMax = kvpRange.Key; DateTime dtMax = DateTime.MinValue; - List vNeighborSrc = null; - for(uint u = kvpRange.Key; u <= kvpRange.Value; ++u) + for(int i = kvpRange.Key; i <= kvpRange.Value; ++i) { - T pt = vItems.GetAt(u); - - // IStructureItem ptOrg = pgOrgStructure.FindObject(pt.Uuid, true, bEntries); - IStructureItem ptOrg = ppOrgStructure.Get(pt.Uuid); - if((ptOrg != null) && (ptOrg.LocationChanged > dtMax)) + PwObjectBlock b = lBlocks[i]; + if(b.LocationChanged > dtMax) { - uPosMax = u; - dtMax = ptOrg.LocationChanged; // No 'continue' - vNeighborSrc = ptOrg.ParentGroup.GetObjects(false, bEntries); - } - - // IStructureItem ptSrc = pgSrcStructure.FindObject(pt.Uuid, true, bEntries); - IStructureItem ptSrc = ppSrcStructure.Get(pt.Uuid); - if((ptSrc != null) && (ptSrc.LocationChanged > dtMax)) - { - uPosMax = u; - dtMax = ptSrc.LocationChanged; // No 'continue' - vNeighborSrc = ptSrc.ParentGroup.GetObjects(false, bEntries); + iPosMax = i; + dtMax = b.LocationChanged; + pPool = b.PoolAssoc; } } - GetNeighborItems(vNeighborSrc, vItems.GetAt(uPosMax).Uuid, qBefore, qAfter); - return uPosMax; + return iPosMax; } - private static void GetNeighborItems(List vItems, - PwUuid pwPivot, Queue qBefore, Queue qAfter) + private static void MergeInLocationChanged(PwGroup pg, + PwObjectPoolEx ppOrg, PwObjectPoolEx ppSrc) { - qBefore.Clear(); - qAfter.Clear(); - - // Checks after clearing the queues - if(vItems == null) { Debug.Assert(false); return; } // No throw - - bool bBefore = true; - for(int i = 0; i < vItems.Count; ++i) + GroupHandler gh = delegate(PwGroup pgSub) { - PwUuid pw = vItems[i].Uuid; + DateTime dt; + if(GetBestPool(pgSub, ppOrg, ppSrc, out dt) != null) + pgSub.LocationChanged = dt; + else { Debug.Assert(false); } + return true; + }; - if(pw.Equals(pwPivot)) bBefore = false; - else if(bBefore) qBefore.Enqueue(pw); - else qAfter.Enqueue(pw); - } - Debug.Assert(bBefore == false); + EntryHandler eh = delegate(PwEntry pe) + { + DateTime dt; + if(GetBestPool(pe, ppOrg, ppSrc, out dt) != null) + pe.LocationChanged = dt; + else { Debug.Assert(false); } + return true; + }; + + gh(pg); + pg.TraverseTree(TraversalMethod.PreOrder, gh, eh); } - /// - /// Method to check whether a reordering is required. This fast test - /// allows to skip the reordering routine, resulting in a large - /// performance increase. - /// - private bool ObjectListRequiresReorder(PwObjectList vItems, - PwObjectPool ppOrgStructure, PwObjectPool ppSrcStructure, bool bEntries) - where T : class, IStructureItem, IDeepCloneable + private static void InsertObjectAtBestPos(PwObjectList lItems, + T tNew, PwObjectPoolEx ppSrc) + where T : class, ITimeLogger, IStructureItem, IDeepCloneable { - Debug.Assert(ppOrgStructure.ContainsOnlyType(bEntries ? typeof(PwEntry) : typeof(PwGroup))); - Debug.Assert(ppSrcStructure.ContainsOnlyType(bEntries ? typeof(PwEntry) : typeof(PwGroup))); - if(vItems.UCount <= 1) return false; + if(tNew == null) { Debug.Assert(false); return; } - if((m_slStatus != null) && !m_slStatus.ContinueWork()) return false; + ulong idSrc = ppSrc.GetIdByUuid(tNew.Uuid); + if(idSrc == 0) { Debug.Assert(false); lItems.Add(tNew); return; } - T ptFirst = vItems.GetAt(0); - // IStructureItem ptOrg = pgOrgStructure.FindObject(ptFirst.Uuid, true, bEntries); - IStructureItem ptOrg = ppOrgStructure.Get(ptFirst.Uuid); - if(ptOrg == null) return true; - // IStructureItem ptSrc = pgSrcStructure.FindObject(ptFirst.Uuid, true, bEntries); - IStructureItem ptSrc = ppSrcStructure.Get(ptFirst.Uuid); - if(ptSrc == null) return true; + const uint uIdOffset = 2; + Dictionary dOrg = new Dictionary(); + for(uint u = 0; u < lItems.UCount; ++u) + dOrg[lItems.GetAt(u).Uuid] = uIdOffset + u; - if(ptFirst.ParentGroup == null) { Debug.Assert(false); return true; } - PwGroup pgOrgParent = ptOrg.ParentGroup; - if(pgOrgParent == null) return true; // Root might be in tree - PwGroup pgSrcParent = ptSrc.ParentGroup; - if(pgSrcParent == null) return true; // Root might be in tree - - if(!ptFirst.ParentGroup.Uuid.Equals(pgOrgParent.Uuid)) return true; - if(!pgOrgParent.Uuid.Equals(pgSrcParent.Uuid)) return true; - - List lOrg = pgOrgParent.GetObjects(false, bEntries); - List lSrc = pgSrcParent.GetObjects(false, bEntries); - if(vItems.UCount != (uint)lOrg.Count) return true; - if(lOrg.Count != lSrc.Count) return true; - - for(uint u = 0; u < vItems.UCount; ++u) + ulong idSrcNext = idSrc + 1; + uint idOrgNext = 0; + while(true) { - IStructureItem pt = vItems.GetAt(u); - Debug.Assert(pt.ParentGroup == ptFirst.ParentGroup); - - if(!pt.Uuid.Equals(lOrg[(int)u].Uuid)) return true; - if(!pt.Uuid.Equals(lSrc[(int)u].Uuid)) return true; - if(pt.LocationChanged != lOrg[(int)u].LocationChanged) return true; - if(pt.LocationChanged != lSrc[(int)u].LocationChanged) return true; + IStructureItem pNext = ppSrc.GetItemById(idSrcNext); + if(pNext == null) break; + if(dOrg.TryGetValue(pNext.Uuid, out idOrgNext)) break; + ++idSrcNext; } - return false; + if(idOrgNext != 0) + { + lItems.Insert(idOrgNext - uIdOffset, tNew); + return; + } + + ulong idSrcPrev = idSrc - 1; + uint idOrgPrev = 0; + while(true) + { + IStructureItem pPrev = ppSrc.GetItemById(idSrcPrev); + if(pPrev == null) break; + if(dOrg.TryGetValue(pPrev.Uuid, out idOrgPrev)) break; + --idSrcPrev; + } + + if(idOrgPrev != 0) + { + lItems.Insert(idOrgPrev + 1 - uIdOffset, tNew); + return; + } + + lItems.Add(tNew); } - private void MergeInDbProperties(PwDatabase pwSource, PwMergeMethod mm) + private void MergeInDbProperties(PwDatabase pdSource, PwMergeMethod mm) { - if(pwSource == null) { Debug.Assert(false); return; } + if(pdSource == null) { Debug.Assert(false); return; } if((mm == PwMergeMethod.KeepExisting) || (mm == PwMergeMethod.None)) return; bool bForce = (mm == PwMergeMethod.OverwriteExisting); + bool bSourceNewer = (pdSource.m_dtSettingsChanged > m_dtSettingsChanged); - if(bForce || (pwSource.m_dtNameChanged > m_dtNameChanged)) + if(bForce || bSourceNewer) { - m_strName = pwSource.m_strName; - m_dtNameChanged = pwSource.m_dtNameChanged; + m_dtSettingsChanged = pdSource.m_dtSettingsChanged; + + m_clr = pdSource.m_clr; } - if(bForce || (pwSource.m_dtDescChanged > m_dtDescChanged)) + if(bForce || (pdSource.m_dtNameChanged > m_dtNameChanged)) { - m_strDesc = pwSource.m_strDesc; - m_dtDescChanged = pwSource.m_dtDescChanged; + m_strName = pdSource.m_strName; + m_dtNameChanged = pdSource.m_dtNameChanged; } - if(bForce || (pwSource.m_dtDefaultUserChanged > m_dtDefaultUserChanged)) + if(bForce || (pdSource.m_dtDescChanged > m_dtDescChanged)) { - m_strDefaultUserName = pwSource.m_strDefaultUserName; - m_dtDefaultUserChanged = pwSource.m_dtDefaultUserChanged; + m_strDesc = pdSource.m_strDesc; + m_dtDescChanged = pdSource.m_dtDescChanged; } - if(bForce) m_clr = pwSource.m_clr; - - PwUuid pwPrefBin = m_pwRecycleBin, pwAltBin = pwSource.m_pwRecycleBin; - if(bForce || (pwSource.m_dtRecycleBinChanged > m_dtRecycleBinChanged)) + if(bForce || (pdSource.m_dtDefaultUserChanged > m_dtDefaultUserChanged)) { - pwPrefBin = pwSource.m_pwRecycleBin; + m_strDefaultUserName = pdSource.m_strDefaultUserName; + m_dtDefaultUserChanged = pdSource.m_dtDefaultUserChanged; + } + + PwUuid pwPrefBin = m_pwRecycleBin, pwAltBin = pdSource.m_pwRecycleBin; + if(bForce || (pdSource.m_dtRecycleBinChanged > m_dtRecycleBinChanged)) + { + pwPrefBin = pdSource.m_pwRecycleBin; pwAltBin = m_pwRecycleBin; - m_bUseRecycleBin = pwSource.m_bUseRecycleBin; - m_dtRecycleBinChanged = pwSource.m_dtRecycleBinChanged; + m_bUseRecycleBin = pdSource.m_bUseRecycleBin; + m_dtRecycleBinChanged = pdSource.m_dtRecycleBinChanged; } if(m_pgRootGroup.FindGroup(pwPrefBin, true) != null) m_pwRecycleBin = pwPrefBin; @@ -1325,18 +1512,28 @@ namespace KeePassLib m_pwRecycleBin = pwAltBin; else m_pwRecycleBin = PwUuid.Zero; // Debug.Assert(false); - PwUuid pwPrefTmp = m_pwEntryTemplatesGroup, pwAltTmp = pwSource.m_pwEntryTemplatesGroup; - if(bForce || (pwSource.m_dtEntryTemplatesChanged > m_dtEntryTemplatesChanged)) + PwUuid pwPrefTmp = m_pwEntryTemplatesGroup, pwAltTmp = pdSource.m_pwEntryTemplatesGroup; + if(bForce || (pdSource.m_dtEntryTemplatesChanged > m_dtEntryTemplatesChanged)) { - pwPrefTmp = pwSource.m_pwEntryTemplatesGroup; + pwPrefTmp = pdSource.m_pwEntryTemplatesGroup; pwAltTmp = m_pwEntryTemplatesGroup; - m_dtEntryTemplatesChanged = pwSource.m_dtEntryTemplatesChanged; + m_dtEntryTemplatesChanged = pdSource.m_dtEntryTemplatesChanged; } if(m_pgRootGroup.FindGroup(pwPrefTmp, true) != null) m_pwEntryTemplatesGroup = pwPrefTmp; else if(m_pgRootGroup.FindGroup(pwAltTmp, true) != null) m_pwEntryTemplatesGroup = pwAltTmp; else m_pwEntryTemplatesGroup = PwUuid.Zero; // Debug.Assert(false); + + foreach(KeyValuePair kvp in pdSource.m_dCustomData) + { + if(bSourceNewer || !m_dCustomData.Exists(kvp.Key)) + m_dCustomData.Set(kvp.Key, kvp.Value); + } + + VariantDictionary vdLocal = m_dPublicCustomData; // Backup + m_dPublicCustomData = (VariantDictionary)pdSource.m_dPublicCustomData.Clone(); + if(!bSourceNewer) vdLocal.CopyTo(m_dPublicCustomData); // Merge } private void MergeEntryHistory(PwEntry pe, PwEntry peSource, @@ -1414,12 +1611,12 @@ namespace KeePassLib /// Source file. public void Synchronize(string strFile) { - PwDatabase pwSource = new PwDatabase(); + PwDatabase pdSource = new PwDatabase(); IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); - pwSource.Open(ioc, m_pwUserKey, null); + pdSource.Open(ioc, m_pwUserKey, null); - MergeIn(pwSource, PwMergeMethod.Synchronize); + MergeIn(pdSource, PwMergeMethod.Synchronize); } */ /// @@ -1534,33 +1731,97 @@ namespace KeePassLib RemoveCustomIconUuid(peHistory, vToDelete); } - private bool ValidateUuidUniqueness() + private int GetTotalObjectUuidCount() { -#if DEBUG - List l = new List(); - bool bAllUnique = true; + uint uGroups, uEntries; + m_pgRootGroup.GetCounts(true, out uGroups, out uEntries); + + uint uTotal = uGroups + uEntries + 1; // 1 for root group + if(uTotal > 0x7FFFFFFFU) { Debug.Assert(false); return 0x7FFFFFFF; } + return (int)uTotal; + } + + internal bool HasDuplicateUuids() + { + int nTotal = GetTotalObjectUuidCount(); + Dictionary d = new Dictionary(nTotal); + bool bDupFound = false; GroupHandler gh = delegate(PwGroup pg) { - foreach(PwUuid u in l) - bAllUnique &= !pg.Uuid.Equals(u); - l.Add(pg.Uuid); - return bAllUnique; + PwUuid pu = pg.Uuid; + if(d.ContainsKey(pu)) + { + bDupFound = true; + return false; + } + + d.Add(pu, null); + Debug.Assert(d.ContainsKey(pu)); + return true; }; EntryHandler eh = delegate(PwEntry pe) { - foreach(PwUuid u in l) - bAllUnique &= !pe.Uuid.Equals(u); - l.Add(pe.Uuid); - return bAllUnique; + PwUuid pu = pe.Uuid; + if(d.ContainsKey(pu)) + { + bDupFound = true; + return false; + } + + d.Add(pu, null); + Debug.Assert(d.ContainsKey(pu)); + return true; }; + gh(m_pgRootGroup); m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh); - return bAllUnique; -#else - return true; -#endif + + Debug.Assert(bDupFound || (d.Count == nTotal)); + return bDupFound; + } + + internal void FixDuplicateUuids() + { + int nTotal = GetTotalObjectUuidCount(); + Dictionary d = new Dictionary(nTotal); + + GroupHandler gh = delegate(PwGroup pg) + { + PwUuid pu = pg.Uuid; + if(d.ContainsKey(pu)) + { + pu = new PwUuid(true); + while(d.ContainsKey(pu)) { Debug.Assert(false); pu = new PwUuid(true); } + + pg.Uuid = pu; + } + + d.Add(pu, null); + return true; + }; + + EntryHandler eh = delegate(PwEntry pe) + { + PwUuid pu = pe.Uuid; + if(d.ContainsKey(pu)) + { + pu = new PwUuid(true); + while(d.ContainsKey(pu)) { Debug.Assert(false); pu = new PwUuid(true); } + + pe.SetUuid(pu, true); + } + + d.Add(pu, null); + return true; + }; + + gh(m_pgRootGroup); + m_pgRootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh); + + Debug.Assert(d.Count == nTotal); + Debug.Assert(!HasDuplicateUuids()); } /* public void CreateBackupFile(IStatusLogger sl) diff --git a/src/KeePassLib2Android/PwDefs.cs b/src/KeePassLib2Android/PwDefs.cs index ec563a39..b7ddd6c6 100644 --- a/src/KeePassLib2Android/PwDefs.cs +++ b/src/KeePassLib2Android/PwDefs.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,9 +19,9 @@ using System; using System.Collections.Generic; -using System.Xml.Serialization; using System.ComponentModel; using System.Diagnostics; +using System.Xml.Serialization; using KeePassLib.Delegates; using KeePassLib.Interfaces; @@ -55,20 +55,20 @@ namespace KeePassLib /// e.g. 2.19 = 0x02130000. /// It is highly recommended to use FileVersion64 instead. /// - public const uint Version32 = 0x02180000; + public const uint Version32 = 0x02220000; /// /// Version, encoded as 64-bit unsigned integer /// (component-wise, 16 bits per component). /// - public const ulong FileVersion64 = 0x0002001800000000UL; + public const ulong FileVersion64 = 0x0002002200000000UL; /// /// Version, encoded as string. /// - public const string VersionString = "2.24"; + public const string VersionString = "2.34"; - public const string Copyright = @"Copyright © 2003-2013 Dominik Reichl"; + public const string Copyright = @"Copyright © 2003-2016 Dominik Reichl"; /// /// Product website URL. Terminated by a forward slash. @@ -94,7 +94,8 @@ namespace KeePassLib /// URL to a TXT file (eventually compressed) that contains information /// about the latest KeePass version available on the website. /// - public const string VersionUrl = "http://keepass.info/update/version2x.txt.gz"; + public const string VersionUrl = "https://sslsites.de/keepass.info/update/version2x.txt.gz"; + // public const string VersionUrl = "http://keepass.info/update/version2x.txt.gz"; /// /// URL to the root path of the online KeePass help. Terminated by @@ -220,7 +221,7 @@ namespace KeePassLib } } - #pragma warning disable 1591 // Missing XML comments warning + // #pragma warning disable 1591 // Missing XML comments warning /// /// Search parameters for group and entry searches. /// @@ -318,7 +319,7 @@ namespace KeePassLib set { m_bSearchInTags = value; } } -#if KeePassRT +#if KeePassUAP private StringComparison m_scType = StringComparison.OrdinalIgnoreCase; #else private StringComparison m_scType = StringComparison.InvariantCultureIgnoreCase; @@ -410,9 +411,9 @@ namespace KeePassLib return (SearchParameters)this.MemberwiseClone(); } } - #pragma warning restore 1591 // Missing XML comments warning + // #pragma warning restore 1591 // Missing XML comments warning - #pragma warning disable 1591 // Missing XML comments warning + // #pragma warning disable 1591 // Missing XML comments warning /// /// Memory protection configuration structure (for default fields). /// @@ -442,7 +443,7 @@ namespace KeePassLib return false; } } - #pragma warning restore 1591 // Missing XML comments warning + // #pragma warning restore 1591 // Missing XML comments warning public sealed class ObjectTouchedEventArgs : EventArgs { diff --git a/src/KeePassLib2Android/PwDeletedObject.cs b/src/KeePassLib2Android/PwDeletedObject.cs index 2ba803e6..734fe345 100644 --- a/src/KeePassLib2Android/PwDeletedObject.cs +++ b/src/KeePassLib2Android/PwDeletedObject.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/PwEntry.cs b/src/KeePassLib2Android/PwEntry.cs index 69846a91..22b87468 100644 --- a/src/KeePassLib2Android/PwEntry.cs +++ b/src/KeePassLib2Android/PwEntry.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -20,8 +20,10 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Xml; + +#if !KeePassUAP using System.Drawing; +#endif using KeePassLib.Collections; using KeePassLib.Interfaces; @@ -70,9 +72,11 @@ namespace KeePassLib private List m_vTags = new List(); + private StringDictionaryEx m_dCustomData = new StringDictionaryEx(); /// /// UUID of this entry. /// + /// public PwUuid Uuid { get { return m_uuid; } @@ -304,6 +308,23 @@ namespace KeePassLib } } + /// + /// Custom data container that can be used by plugins to store + /// own data in KeePass entries. + /// The data is stored in the encrypted part of encrypted + /// database files. + /// Use unique names for your items, e.g. "PluginName_ItemName". + /// + public StringDictionaryEx CustomData + { + get { return m_dCustomData; } + internal set + { + if(value == null) { Debug.Assert(false); throw new ArgumentNullException("value"); } + m_dCustomData = value; + } + } + public static EventHandler EntryTouched; public EventHandler Touched; @@ -352,12 +373,20 @@ namespace KeePassLib } } +#if DEBUG /// + public override string ToString() + { + return (@"PwEntry '" + m_listStrings.ReadSafe(PwDefs.TitleField) + @"'"); + } +#endif /// Clone the current entry. The returned entry is an exact value copy /// of the current entry (including UUID and parent group reference). /// All mutable members are cloned. /// /// Exact value clone. All references to mutable values changed. + /// + /// Exact value clone. All references to mutable values changed. public PwEntry CloneDeep() { PwEntry peNew = new PwEntry(false, false); @@ -394,6 +423,8 @@ namespace KeePassLib peNew.m_vTags = new List(m_vTags); + peNew.m_dCustomData = m_dCustomData.CloneDeep(); + return peNew; } @@ -515,6 +546,8 @@ namespace KeePassLib if(m_vTags[iTag] != pe.m_vTags[iTag]) return false; } + if(!m_dCustomData.Equals(pe.m_dCustomData)) return false; + return true; } @@ -531,7 +564,7 @@ namespace KeePassLib public void AssignProperties(PwEntry peTemplate, bool bOnlyIfNewer, bool bIncludeHistory, bool bAssignLocationChanged) { - Debug.Assert(peTemplate != null); if(peTemplate == null) throw new ArgumentNullException("peTemplate"); + if(peTemplate == null) { Debug.Assert(false); throw new ArgumentNullException("peTemplate"); } if(bOnlyIfNewer && (TimeUtil.Compare(peTemplate.LastModificationTime,LastModificationTime,true) < 0)) return; @@ -542,10 +575,11 @@ namespace KeePassLib if(bAssignLocationChanged) m_tParentGroupLastMod = peTemplate.LocationChanged; - m_listStrings = peTemplate.m_listStrings; - m_listBinaries = peTemplate.m_listBinaries; - m_listAutoType = peTemplate.m_listAutoType; - if(bIncludeHistory) m_listHistory = peTemplate.m_listHistory; + m_listStrings = peTemplate.m_listStrings.CloneDeep(); + m_listBinaries = peTemplate.m_listBinaries.CloneDeep(); + m_listAutoType = peTemplate.m_listAutoType.CloneDeep(); + if(bIncludeHistory) + m_listHistory = peTemplate.m_listHistory.CloneDeep(); m_pwIcon = peTemplate.m_pwIcon; m_pwCustomIconID = peTemplate.m_pwCustomIconID; // Immutable @@ -563,6 +597,8 @@ namespace KeePassLib m_strOverrideUrl = peTemplate.m_strOverrideUrl; m_vTags = new List(peTemplate.m_vTags); + + m_dCustomData = peTemplate.m_dCustomData.CloneDeep(); } /// @@ -814,6 +850,9 @@ namespace KeePassLib foreach(string strTag in m_vTags) uSize += (ulong)strTag.Length; + foreach(KeyValuePair kvp in m_dCustomData) + uSize += (ulong)kvp.Key.Length + (ulong)kvp.Value.Length; + return uSize; } @@ -893,6 +932,25 @@ namespace KeePassLib } return dateTime; } + + + public void SetCreatedNow() + { + DateTime dt = DateTime.Now; + + m_tCreation = dt; + m_tLastAccess = dt; + } + + public PwEntry Duplicate() + { + PwEntry pe = CloneDeep(); + + pe.SetUuid(new PwUuid(true), true); + pe.SetCreatedNow(); + + return pe; + } } public sealed class PwEntryComparer : IComparer @@ -918,12 +976,7 @@ namespace KeePassLib if(m_bCompareNaturally) return StrUtil.CompareNaturally(strA, strB); -#if KeePassRT - return string.Compare(strA, strB, m_bCaseInsensitive ? - StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture); -#else return string.Compare(strA, strB, m_bCaseInsensitive); -#endif } } } diff --git a/src/KeePassLib2Android/PwEnums.cs b/src/KeePassLib2Android/PwEnums.cs index c6dd8673..13bed411 100644 --- a/src/KeePassLib2Android/PwEnums.cs +++ b/src/KeePassLib2Android/PwEnums.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -163,6 +163,26 @@ namespace KeePassLib Manual = 2 } + public enum ProxyAuthType + { + None = 0, + + /// + /// Use default user credentials (provided by the system). + /// + Default = 1, + + Manual = 2, + + /// + /// Default or Manual, depending on whether + /// manual credentials are available. + /// This type exists for supporting upgrading from KeePass + /// 2.28 to 2.29; the user cannot select this type. + /// + Auto = 3 + } + /// /// Comparison modes for in-memory protected objects. /// @@ -204,6 +224,9 @@ namespace KeePassLib IgnoreHistory = 0x10, IgnoreLastBackup = 0x20, + // For groups: + PropertiesOnly = 0x40, + IgnoreTimes = (IgnoreLastAccess | IgnoreLastMod) } @@ -254,14 +277,43 @@ namespace KeePassLib GetStdOutput = 1, WaitForExit = 2, - // This flag prevents any handles being garbage-collected - // before the started process has terminated, without - // blocking the current thread; // https://sourceforge.net/p/keepass/patches/84/ + /// + /// This flag prevents any handles being garbage-collected + /// before the started process has terminated, without + /// blocking the current thread. + /// GCKeepAlive = 4, // https://sourceforge.net/p/keepass/patches/85/ DoEvents = 8, DisableForms = 16 } + + [Flags] + public enum ScaleTransformFlags + { + None = 0, + + /// + /// UIIcon indicates that the returned image is going + /// to be displayed as icon in the UI and that it is not + /// subject to future changes in size. + /// + UIIcon = 1 + } + + public enum DesktopType + { + None = 0, + Windows, + Gnome, + Kde, + Unity, + Lxde, + Xfce, + Mate, + Cinnamon, + Pantheon + } } diff --git a/src/KeePassLib2Android/PwGroup.cs b/src/KeePassLib2Android/PwGroup.cs index 793ff3bc..e5256c19 100644 --- a/src/KeePassLib2Android/PwGroup.cs +++ b/src/KeePassLib2Android/PwGroup.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -60,15 +60,15 @@ namespace KeePassLib private DateTime m_tLastMod = PwDefs.DtDefaultNow; private DateTime m_tLastAccess = PwDefs.DtDefaultNow; private DateTime m_tExpire = PwDefs.DtDefaultNow; + private bool m_bExpires = false; + private ulong m_uUsageCount = 0; + private string m_tCreationLazy; private string m_tLastModLazy; private string m_tLastAccessLazy; private string m_tExpireLazy; - private bool m_bExpires = false; - private ulong m_uUsageCount = 0; - private bool m_bIsExpanded = true; private bool m_bVirtual = false; @@ -79,6 +79,8 @@ namespace KeePassLib private PwUuid m_pwLastTopVisibleEntry = PwUuid.Zero; + private StringDictionaryEx m_dCustomData = new StringDictionaryEx(); + /// /// UUID of this group. /// @@ -87,7 +89,7 @@ namespace KeePassLib get { return m_uuid; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_uuid = value; } } @@ -100,7 +102,7 @@ namespace KeePassLib get { return m_strName; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_strName = value; } } @@ -113,7 +115,7 @@ namespace KeePassLib get { return m_strNotes; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_strNotes = value; } } @@ -137,7 +139,7 @@ namespace KeePassLib get { return m_pwCustomIconID; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_pwCustomIconID = value; } } @@ -149,7 +151,7 @@ namespace KeePassLib { get { return m_pParentGroup; } - /// Plugins: use PwGroup.AddGroup instead. + // Plugins: use PwGroup.AddGroup instead. internal set { Debug.Assert(value != this); m_pParentGroup = value; } } @@ -161,7 +163,6 @@ namespace KeePassLib get { return GetLazyTime(ref m_tParentGroupLastModLazy, ref m_tParentGroupLastMod); } set { m_tParentGroupLastMod = value; m_tParentGroupLastModLazy = null; } } - public void SetLazyLocationChanged(string xmlDateTime) { m_tParentGroupLastModLazy = xmlDateTime; @@ -191,20 +192,6 @@ namespace KeePassLib m_tCreationLazy = xmlDateTime; } - /// - /// The date/time when this group was last accessed (read). - /// - public DateTime LastAccessTime - { - get { return GetLazyTime(ref m_tLastAccessLazy, ref m_tLastAccess); } - set { m_tLastAccess = value; m_tLastAccessLazy = null; } - } - - public void SetLazyLastAccessTime(string xmlDateTime) - { - m_tLastAccessLazy = xmlDateTime; - } - /// /// The date/time when this group was last modified. /// @@ -220,15 +207,27 @@ namespace KeePassLib } /// - /// The date/time when this group expires. Use the Expires property - /// to specify if the group does actually expire or not. + /// The date/time when this group was last accessed (read). + /// + public DateTime LastAccessTime + { + get { return GetLazyTime(ref m_tLastAccessLazy, ref m_tLastAccess); } + set { m_tLastAccess = value; m_tLastAccessLazy = null; } + } + + public void SetLazyLastAccessTime(string xmlDateTime) + { + m_tLastAccessLazy = xmlDateTime; + } + + /// + /// The date/time when this group expires. /// public DateTime ExpiryTime { get { return GetLazyTime(ref m_tExpireLazy, ref m_tExpire); } set { m_tExpire = value; m_tExpireLazy = null; } } - public void SetLazyExpiryTime(string xmlDateTime) { m_tExpireLazy = xmlDateTime; @@ -292,7 +291,7 @@ namespace KeePassLib get { return m_strDefaultAutoTypeSequence; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_strDefaultAutoTypeSequence = value; } } @@ -314,11 +313,28 @@ namespace KeePassLib get { return m_pwLastTopVisibleEntry; } set { - Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value"); + Debug.Assert(value != null); if (value == null) throw new ArgumentNullException("value"); m_pwLastTopVisibleEntry = value; } } + /// + /// Custom data container that can be used by plugins to store + /// own data in KeePass groups. + /// The data is stored in the encrypted part of encrypted + /// database files. + /// Use unique names for your items, e.g. "PluginName_ItemName". + /// + public StringDictionaryEx CustomData + { + get { return m_dCustomData; } + internal set + { + if (value == null) { Debug.Assert(false); throw new ArgumentNullException("value"); } + m_dCustomData = value; + } + } + public static EventHandler GroupTouched; public EventHandler Touched; @@ -336,9 +352,9 @@ namespace KeePassLib /// Set creation, last access and last modification times to the current time. public PwGroup(bool bCreateNewUuid, bool bSetTimes) { - if(bCreateNewUuid) m_uuid = new PwUuid(true); + if (bCreateNewUuid) m_uuid = new PwUuid(true); - if(bSetTimes) + if (bSetTimes) { m_tCreation = m_tLastMod = m_tLastAccess = m_tParentGroupLastMod = DateTime.Now; @@ -354,19 +370,27 @@ namespace KeePassLib /// Icon of the new group. public PwGroup(bool bCreateNewUuid, bool bSetTimes, string strName, PwIcon pwIcon) { - if(bCreateNewUuid) m_uuid = new PwUuid(true); + if (bCreateNewUuid) m_uuid = new PwUuid(true); - if(bSetTimes) + if (bSetTimes) { m_tCreation = m_tLastMod = m_tLastAccess = m_tParentGroupLastMod = DateTime.Now; } - if(strName != null) m_strName = strName; + if (strName != null) m_strName = strName; m_pwIcon = pwIcon; } +#if DEBUG + // For display in debugger + public override string ToString() + { + return (@"PwGroup '" + m_strName + @"'"); + } +#endif + /// /// Deeply clone the current group. The returned group will be an exact /// value copy of the current object (including UUID, etc.). @@ -391,9 +415,9 @@ namespace KeePassLib pg.m_pwCustomIconID = m_pwCustomIconID; pg.m_tCreation = m_tCreation; - pg.m_tExpire = m_tExpire; - pg.m_tLastAccess = m_tLastAccess; pg.m_tLastMod = m_tLastMod; + pg.m_tLastAccess = m_tLastAccess; + pg.m_tExpire = m_tExpire; pg.m_bExpires = m_bExpires; pg.m_uUsageCount = m_uUsageCount; @@ -407,8 +431,13 @@ namespace KeePassLib pg.m_strDefaultAutoTypeSequence = m_strDefaultAutoTypeSequence; + pg.m_bEnableAutoType = m_bEnableAutoType; + pg.m_bEnableSearching = m_bEnableSearching; + pg.m_pwLastTopVisibleEntry = m_pwLastTopVisibleEntry; + pg.m_dCustomData = m_dCustomData.CloneDeep(); + return pg; } @@ -420,15 +449,87 @@ namespace KeePassLib pg.m_tParentGroupLastMod = m_tParentGroupLastMod; // Do not assign m_pParentGroup - foreach(PwGroup pgSub in m_listGroups) + foreach (PwGroup pgSub in m_listGroups) pg.AddGroup(pgSub.CloneStructure(), true); - foreach(PwEntry peSub in m_listEntries) + foreach (PwEntry peSub in m_listEntries) pg.AddEntry(peSub.CloneStructure(), true); return pg; } + public bool EqualsGroup(PwGroup pg, PwCompareOptions pwOpt, + MemProtCmpMode mpCmpStr) + { + if (pg == null) { Debug.Assert(false); return false; } + + bool bIgnoreLastAccess = ((pwOpt & PwCompareOptions.IgnoreLastAccess) != + PwCompareOptions.None); + bool bIgnoreLastMod = ((pwOpt & PwCompareOptions.IgnoreLastMod) != + PwCompareOptions.None); + + if (!m_uuid.Equals(pg.m_uuid)) return false; + if ((pwOpt & PwCompareOptions.IgnoreParentGroup) == PwCompareOptions.None) + { + if (m_pParentGroup != pg.m_pParentGroup) return false; + if (!bIgnoreLastMod && (m_tParentGroupLastMod != pg.m_tParentGroupLastMod)) + return false; + } + + if (m_strName != pg.m_strName) return false; + if (m_strNotes != pg.m_strNotes) return false; + + if (m_pwIcon != pg.m_pwIcon) return false; + if (!m_pwCustomIconID.Equals(pg.m_pwCustomIconID)) return false; + + if (m_tCreation != pg.m_tCreation) return false; + if (!bIgnoreLastMod && (LastModificationTime != pg.LastModificationTime)) return false; + if (!bIgnoreLastAccess && (m_tLastAccess != pg.m_tLastAccess)) return false; + if (m_tExpire != pg.m_tExpire) return false; + if (m_bExpires != pg.m_bExpires) return false; + if (!bIgnoreLastAccess && (m_uUsageCount != pg.m_uUsageCount)) return false; + + // if(m_bIsExpanded != pg.m_bIsExpanded) return false; + + if (m_strDefaultAutoTypeSequence != pg.m_strDefaultAutoTypeSequence) return false; + + if (m_bEnableAutoType.HasValue != pg.m_bEnableAutoType.HasValue) return false; + if (m_bEnableAutoType.HasValue) + { + if (m_bEnableAutoType.Value != pg.m_bEnableAutoType.Value) return false; + } + if (m_bEnableSearching.HasValue != pg.m_bEnableSearching.HasValue) return false; + if (m_bEnableSearching.HasValue) + { + if (m_bEnableSearching.Value != pg.m_bEnableSearching.Value) return false; + } + + if (!m_pwLastTopVisibleEntry.Equals(pg.m_pwLastTopVisibleEntry)) return false; + + if (!m_dCustomData.Equals(pg.m_dCustomData)) return false; + + if ((pwOpt & PwCompareOptions.PropertiesOnly) == PwCompareOptions.None) + { + if (m_listEntries.UCount != pg.m_listEntries.UCount) return false; + for (uint u = 0; u < m_listEntries.UCount; ++u) + { + PwEntry peA = m_listEntries.GetAt(u); + PwEntry peB = pg.m_listEntries.GetAt(u); + if (!peA.EqualsEntry(peB, pwOpt, mpCmpStr)) return false; + } + + if (m_listGroups.UCount != pg.m_listGroups.UCount) return false; + for (uint u = 0; u < m_listGroups.UCount; ++u) + { + PwGroup pgA = m_listGroups.GetAt(u); + PwGroup pgB = pg.m_listGroups.GetAt(u); + if (!pgA.EqualsGroup(pgB, pwOpt, mpCmpStr)) return false; + } + } + + return true; + } + /// /// Assign properties to the current group based on a template group. /// @@ -440,15 +541,17 @@ namespace KeePassLib public void AssignProperties(PwGroup pgTemplate, bool bOnlyIfNewer, bool bAssignLocationChanged) { - Debug.Assert(pgTemplate != null); if(pgTemplate == null) throw new ArgumentNullException("pgTemplate"); + Debug.Assert(pgTemplate != null); if (pgTemplate == null) throw new ArgumentNullException("pgTemplate"); - if(bOnlyIfNewer && (TimeUtil.Compare(pgTemplate.LastModificationTime,LastModificationTime, true) < 0)) return; + if (bOnlyIfNewer && (TimeUtil.Compare(pgTemplate.LastModificationTime, LastModificationTime, + true) < 0)) + return; // Template UUID should be the same as the current one Debug.Assert(m_uuid.Equals(pgTemplate.m_uuid)); m_uuid = pgTemplate.m_uuid; - if(bAssignLocationChanged) + if (bAssignLocationChanged) m_tParentGroupLastMod = pgTemplate.m_tParentGroupLastMod; m_strName = pgTemplate.m_strName; @@ -461,12 +564,18 @@ namespace KeePassLib m_tLastMod = pgTemplate.LastModificationTime; m_tLastAccess = pgTemplate.LastAccessTime; m_tExpire = pgTemplate.ExpiryTime; + m_bExpires = pgTemplate.m_bExpires; m_uUsageCount = pgTemplate.m_uUsageCount; m_strDefaultAutoTypeSequence = pgTemplate.m_strDefaultAutoTypeSequence; + m_bEnableAutoType = pgTemplate.m_bEnableAutoType; + m_bEnableSearching = pgTemplate.m_bEnableSearching; + m_pwLastTopVisibleEntry = pgTemplate.m_pwLastTopVisibleEntry; + + m_dCustomData = pgTemplate.m_dCustomData.CloneDeep(); } /// @@ -493,16 +602,16 @@ namespace KeePassLib m_tLastAccess = DateTime.Now; ++m_uUsageCount; - if(bModified) m_tLastMod = m_tLastAccess; + if (bModified) m_tLastMod = m_tLastAccess; - if(this.Touched != null) + if (this.Touched != null) this.Touched(this, new ObjectTouchedEventArgs(this, bModified, bTouchParents)); - if(PwGroup.GroupTouched != null) + if (PwGroup.GroupTouched != null) PwGroup.GroupTouched(this, new ObjectTouchedEventArgs(this, bModified, bTouchParents)); - if(bTouchParents && (m_pParentGroup != null)) + if (bTouchParents && (m_pParentGroup != null)) m_pParentGroup.Touch(bModified, true); } @@ -519,13 +628,13 @@ namespace KeePassLib /// Number of entries. public void GetCounts(bool bRecursive, out uint uNumGroups, out uint uNumEntries) { - if(bRecursive) + if (bRecursive) { uint uTotalGroups = m_listGroups.UCount; uint uTotalEntries = m_listEntries.UCount; uint uSubGroupCount, uSubEntryCount; - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { pg.GetCounts(true, out uSubGroupCount, out uSubEntryCount); @@ -569,7 +678,7 @@ namespace KeePassLib { bool bRet = false; - switch(tm) + switch (tm) { case TraversalMethod.None: bRet = true; @@ -587,26 +696,26 @@ namespace KeePassLib private bool PreOrderTraverseTree(GroupHandler groupHandler, EntryHandler entryHandler) { - if(entryHandler != null) + if (entryHandler != null) { - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) { - if(!entryHandler(pe)) return false; + if (!entryHandler(pe)) return false; } } - if(groupHandler != null) + if (groupHandler != null) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { - if(!groupHandler(pg)) return false; + if (!groupHandler(pg)) return false; pg.PreOrderTraverseTree(groupHandler, entryHandler); } } else // groupHandler == null { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { pg.PreOrderTraverseTree(null, entryHandler); } @@ -617,19 +726,17 @@ namespace KeePassLib /// /// Pack all groups into one flat linked list of references (recursively). - /// Temporary IDs (TemporaryID field) and levels (TemporaryLevel) - /// are assigned automatically. /// /// Flat list of all groups. public LinkedList GetFlatGroupList() { LinkedList list = new LinkedList(); - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { list.AddLast(pg); - if(pg.Groups.UCount != 0) + if (pg.Groups.UCount != 0) LinearizeGroupRecursive(list, pg, 1); } @@ -638,13 +745,13 @@ namespace KeePassLib private void LinearizeGroupRecursive(LinkedList list, PwGroup pg, ushort uLevel) { - Debug.Assert(pg != null); if(pg == null) return; + Debug.Assert(pg != null); if (pg == null) return; - foreach(PwGroup pwg in pg.Groups) + foreach (PwGroup pwg in pg.Groups) { list.AddLast(pwg); - if(pwg.Groups.UCount != 0) + if (pwg.Groups.UCount != 0) LinearizeGroupRecursive(list, pwg, (ushort)(uLevel + 1)); } } @@ -658,12 +765,12 @@ namespace KeePassLib /// Flat list of all entries. public static LinkedList GetFlatEntryList(LinkedList flatGroupList) { - Debug.Assert(flatGroupList != null); if(flatGroupList == null) return null; + Debug.Assert(flatGroupList != null); if (flatGroupList == null) return null; LinkedList list = new LinkedList(); - foreach(PwGroup pg in flatGroupList) + foreach (PwGroup pg in flatGroupList) { - foreach(PwEntry pe in pg.Entries) + foreach (PwEntry pe in pg.Entries) list.AddLast(pe); } @@ -687,7 +794,7 @@ namespace KeePassLib pe.Strings.EnableProtection(strFieldName, bEnable); // Do the same for all history items - foreach(PwEntry peHistory in pe.History) + foreach (PwEntry peHistory in pe.History) { peHistory.Strings.EnableProtection(strFieldName, bEnable); } @@ -715,6 +822,7 @@ namespace KeePassLib /// Specifies the search method. /// Entry list in which the search results will /// be stored. + /// Optional status reporting object. public void SearchEntries(SearchParameters sp, PwObjectList listStorage, IStatusLogger slStatus) { @@ -731,17 +839,18 @@ namespace KeePassLib public void SearchEntries(SearchParameters sp, PwObjectList listStorage, IDictionary> resultContexts, IStatusLogger slStatus) { - if(sp == null) { Debug.Assert(false); return; } - if(listStorage == null) { Debug.Assert(false); return; } + + if (sp == null) { Debug.Assert(false); return; } + if (listStorage == null) { Debug.Assert(false); return; } ulong uCurEntries = 0, uTotalEntries = 0; List lTerms = StrUtil.SplitSearchTerms(sp.SearchString); - if((lTerms.Count <= 1) || sp.RegularExpression) + if ((lTerms.Count <= 1) || sp.RegularExpression) { - if(slStatus != null) uTotalEntries = GetEntriesCount(true); - SearchEntriesSingle(sp, listStorage, resultContexts , slStatus, ref uCurEntries, - uTotalEntries); + if (slStatus != null) uTotalEntries = GetEntriesCount(true); + SearchEntriesSingle(sp, listStorage, resultContexts, slStatus, ref uCurEntries, + uTotalEntries); return; } @@ -751,10 +860,10 @@ namespace KeePassLib string strFullSearch = sp.SearchString; // Backup PwGroup pg = this; - for(int iTerm = 0; iTerm < lTerms.Count; ++iTerm) + for (int iTerm = 0; iTerm < lTerms.Count; ++iTerm) { // Update counters for a better state guess - if(slStatus != null) + if (slStatus != null) { ulong uRemRounds = (ulong)(lTerms.Count - iTerm); uTotalEntries = uCurEntries + (uRemRounds * @@ -766,33 +875,33 @@ namespace KeePassLib sp.SearchString = lTerms[iTerm]; bool bNegate = false; - if(sp.SearchString.StartsWith("-")) + if (sp.SearchString.StartsWith("-")) { sp.SearchString = sp.SearchString.Substring(1); bNegate = (sp.SearchString.Length > 0); } - if(!pg.SearchEntriesSingle(sp, pgNew.Entries, resultContexts, slStatus, + if (!pg.SearchEntriesSingle(sp, pgNew.Entries, resultContexts, slStatus, ref uCurEntries, uTotalEntries)) { pg = null; break; } - if(bNegate) + if (bNegate) { PwObjectList lCand = pg.GetEntries(true); pg = new PwGroup(); - foreach(PwEntry peCand in lCand) + foreach (PwEntry peCand in lCand) { - if(pgNew.Entries.IndexOf(peCand) < 0) pg.Entries.Add(peCand); + if (pgNew.Entries.IndexOf(peCand) < 0) pg.Entries.Add(peCand); } } else pg = pgNew; } - if(pg != null) listStorage.Add(pg.Entries); + if (pg != null) listStorage.Add(pg.Entries); sp.SearchString = strFullSearch; // Restore } @@ -801,7 +910,7 @@ namespace KeePassLib ref ulong uCurEntries, ulong uTotalEntries) { SearchParameters sp = spIn.Clone(); - if(sp.SearchString == null) { Debug.Assert(false); return true; } + if (sp.SearchString == null) { Debug.Assert(false); return true; } sp.SearchString = sp.SearchString.Trim(); bool bTitle = sp.SearchInTitles; @@ -819,18 +928,14 @@ namespace KeePassLib DateTime dtNow = DateTime.Now; Regex rx = null; - if(sp.RegularExpression) + if (sp.RegularExpression) { -#if KeePassRT - RegexOptions ro = RegexOptions.None; -#else - RegexOptions ro = RegexOptions.Compiled; + RegexOptions ro = RegexOptions.None; // RegexOptions.Compiled + if ((sp.ComparisonMode == StringComparison.CurrentCultureIgnoreCase) || +#if !KeePassUAP + (sp.ComparisonMode == StringComparison.InvariantCultureIgnoreCase) || #endif - if((sp.ComparisonMode == StringComparison.CurrentCultureIgnoreCase) || -#if !KeePassRT - (sp.ComparisonMode == StringComparison.InvariantCultureIgnoreCase) || -#endif - (sp.ComparisonMode == StringComparison.OrdinalIgnoreCase)) + (sp.ComparisonMode == StringComparison.OrdinalIgnoreCase)) { ro |= RegexOptions.IgnoreCase; } @@ -841,20 +946,20 @@ namespace KeePassLib ulong uLocalCurEntries = uCurEntries; EntryHandler eh = null; - if(sp.SearchString.Length <= 0) // Report all + if (sp.SearchString.Length <= 0) // Report all { eh = delegate(PwEntry pe) { - if(slStatus != null) + if (slStatus != null) { - if(!slStatus.SetProgress((uint)((uLocalCurEntries * + if (!slStatus.SetProgress((uint)((uLocalCurEntries * 100UL) / uTotalEntries))) return false; ++uLocalCurEntries; } - if(bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) + if (bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) return true; // Skip - if(bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) + if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) return true; // Skip listStorage.Add(pe); @@ -865,69 +970,69 @@ namespace KeePassLib { eh = delegate(PwEntry pe) { - if(slStatus != null) + if (slStatus != null) { - if(!slStatus.SetProgress((uint)((uLocalCurEntries * + if (!slStatus.SetProgress((uint)((uLocalCurEntries * 100UL) / uTotalEntries))) return false; ++uLocalCurEntries; } - if(bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) + if (bRespectEntrySearchingDisabled && !pe.GetSearchingEnabled()) return true; // Skip - if(bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) + if (bExcludeExpired && pe.Expires && (dtNow > pe.ExpiryTime)) return true; // Skip uint uInitialResults = listStorage.UCount; - foreach(KeyValuePair kvp in pe.Strings) + foreach (KeyValuePair kvp in pe.Strings) { string strKey = kvp.Key; - if(strKey == PwDefs.TitleField) + if (strKey == PwDefs.TitleField) { - if(bTitle) SearchEvalAdd(sp, kvp.Value.ReadString(), - rx, pe, listStorage, resultContexts, strKey); + if (bTitle) SearchEvalAdd(sp, kvp.Value.ReadString(), + rx, pe, listStorage, resultContexts, strKey); } - else if(strKey == PwDefs.UserNameField) + else if (strKey == PwDefs.UserNameField) { - if(bUserName) SearchEvalAdd(sp, kvp.Value.ReadString(), - rx, pe, listStorage, resultContexts, strKey); + if (bUserName) SearchEvalAdd(sp, kvp.Value.ReadString(), + rx, pe, listStorage, resultContexts, strKey); } - else if(strKey == PwDefs.PasswordField) + else if (strKey == PwDefs.PasswordField) { - if(bPassword) SearchEvalAdd(sp, kvp.Value.ReadString(), - rx, pe, listStorage, resultContexts, strKey); + if (bPassword) SearchEvalAdd(sp, kvp.Value.ReadString(), + rx, pe, listStorage, resultContexts, strKey); } - else if(strKey == PwDefs.UrlField) + else if (strKey == PwDefs.UrlField) { - if(bUrl) SearchEvalAdd(sp, kvp.Value.ReadString(), - rx, pe, listStorage, resultContexts, strKey); + if (bUrl) SearchEvalAdd(sp, kvp.Value.ReadString(), + rx, pe, listStorage, resultContexts, strKey); } - else if(strKey == PwDefs.NotesField) + else if (strKey == PwDefs.NotesField) { - if(bNotes) SearchEvalAdd(sp, kvp.Value.ReadString(), - rx, pe, listStorage, resultContexts, strKey); + if (bNotes) SearchEvalAdd(sp, kvp.Value.ReadString(), + rx, pe, listStorage, resultContexts, strKey); } - else if(bOther) + else if (bOther) SearchEvalAdd(sp, kvp.Value.ReadString(), rx, pe, listStorage, resultContexts, strKey); // An entry can match only once => break if we have added it - if(listStorage.UCount > uInitialResults) break; + if (listStorage.UCount > uInitialResults) break; } - if(bUuids && (listStorage.UCount == uInitialResults)) - SearchEvalAdd(sp, pe.Uuid.ToHexString(), rx, pe, listStorage, resultContexts, SearchContextUuid); + if (bUuids && (listStorage.UCount == uInitialResults)) + SearchEvalAdd(sp, pe.Uuid.ToHexString(), rx, pe, listStorage, resultContexts, SearchContextTags); - if(bGroupName && (listStorage.UCount == uInitialResults) && + if (bGroupName && (listStorage.UCount == uInitialResults) && (pe.ParentGroup != null)) SearchEvalAdd(sp, pe.ParentGroup.Name, rx, pe, listStorage, resultContexts, SearchContextParentGroup); - if(bTags) + if (bTags) { - foreach(string strTag in pe.Tags) + foreach (string strTag in pe.Tags) { - if(listStorage.UCount != uInitialResults) break; // Match + if (listStorage.UCount != uInitialResults) break; // Match SearchEvalAdd(sp, strTag, rx, pe, listStorage, resultContexts, SearchContextTags); } @@ -937,7 +1042,7 @@ namespace KeePassLib }; } - if(!PreOrderTraverseTree(null, eh)) return false; + if (!PreOrderTraverseTree(null, eh)) return false; uCurEntries = uLocalCurEntries; return true; } @@ -947,7 +1052,6 @@ namespace KeePassLib { bool bMatch = false; int matchPos; - if (rx == null) { matchPos = strDataField.IndexOf(sp.SearchString, sp.ComparisonMode); @@ -960,10 +1064,10 @@ namespace KeePassLib matchPos = match.Index; } - if(!bMatch && (sp.DataTransformationFn != null)) + if (!bMatch && (sp.DataTransformationFn != null)) { string strCmp = sp.DataTransformationFn(strDataField, pe); - if(!object.ReferenceEquals(strCmp, strDataField)) + if (!object.ReferenceEquals(strCmp, strDataField)) { if (rx == null) { @@ -1009,26 +1113,26 @@ namespace KeePassLib EntryHandler eh = delegate(PwEntry pe) { - foreach(string strTag in pe.Tags) + foreach (string strTag in pe.Tags) { bool bFound = false; - for(int i = 0; i < vTags.Count; ++i) + for (int i = 0; i < vTags.Count; ++i) { - if(vTags[i].Equals(strTag, StrUtil.CaseIgnoreCmp)) + if (vTags[i].Equals(strTag, StrUtil.CaseIgnoreCmp)) { bFound = true; break; } } - if(!bFound) vTags.Add(strTag); + if (!bFound) vTags.Add(strTag); } return true; }; TraverseTree(TraversalMethod.PreOrder, null, eh); - if(bSort) vTags.Sort(StrUtil.CaseIgnoreComparer); + if (bSort) vTags.Sort(StrUtil.CaseIgnoreComparer); return vTags; } @@ -1036,15 +1140,15 @@ namespace KeePassLib public IDictionary BuildEntryTagsDict(bool bSort) { IDictionary d; - if(!bSort) d = new Dictionary(StrUtil.CaseIgnoreComparer); + if (!bSort) d = new Dictionary(StrUtil.CaseIgnoreComparer); else d = new SortedDictionary(StrUtil.CaseIgnoreComparer); EntryHandler eh = delegate(PwEntry pe) { - foreach(string strTag in pe.Tags) + foreach (string strTag in pe.Tags) { uint u; - if(d.TryGetValue(strTag, out u)) d[strTag] = u + 1; + if (d.TryGetValue(strTag, out u)) d[strTag] = u + 1; else d[strTag] = 1; } @@ -1059,14 +1163,14 @@ namespace KeePassLib public void FindEntriesByTag(string strTag, PwObjectList listStorage, bool bSearchRecursive) { - if(strTag == null) throw new ArgumentNullException("strTag"); - if(strTag.Length == 0) return; + if (strTag == null) throw new ArgumentNullException("strTag"); + if (strTag.Length == 0) return; - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) { - foreach(string strEntryTag in pe.Tags) + foreach (string strEntryTag in pe.Tags) { - if(strEntryTag.Equals(strTag, StrUtil.CaseIgnoreCmp)) + if (strEntryTag.Equals(strTag, StrUtil.CaseIgnoreCmp)) { listStorage.Add(pe); break; @@ -1074,9 +1178,9 @@ namespace KeePassLib } } - if(bSearchRecursive) + if (bSearchRecursive) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) pg.FindEntriesByTag(strTag, listStorage, true); } } @@ -1090,22 +1194,22 @@ namespace KeePassLib public PwGroup FindGroup(PwUuid uuid, bool bSearchRecursive) { // Do not assert on PwUuid.Zero - if(m_uuid.Equals(uuid)) return this; + if (m_uuid.Equals(uuid)) return this; - if(bSearchRecursive) + if (bSearchRecursive) { PwGroup pgRec; - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { pgRec = pg.FindGroup(uuid, true); - if(pgRec != null) return pgRec; + if (pgRec != null) return pgRec; } } else // Not recursive { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { - if(pg.m_uuid.Equals(uuid)) + if (pg.m_uuid.Equals(uuid)) return pg; } } @@ -1125,14 +1229,14 @@ namespace KeePassLib public IStructureItem FindObject(PwUuid uuid, bool bRecursive, bool? bEntries) { - if(bEntries.HasValue) + if (bEntries.HasValue) { - if(bEntries.Value) return FindEntry(uuid, bRecursive); + if (bEntries.Value) return FindEntry(uuid, bRecursive); else return FindGroup(uuid, bRecursive); } PwGroup pg = FindGroup(uuid, bRecursive); - if(pg != null) return pg; + if (pg != null) return pg; return FindEntry(uuid, bRecursive); } @@ -1145,14 +1249,14 @@ namespace KeePassLib /// it doesn't exist and shouldn't be created. public PwGroup FindCreateGroup(string strName, bool bCreateIfNotFound) { - Debug.Assert(strName != null); if(strName == null) throw new ArgumentNullException("strName"); + Debug.Assert(strName != null); if (strName == null) throw new ArgumentNullException("strName"); - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { - if(pg.Name == strName) return pg; + if (pg.Name == strName) return pg; } - if(!bCreateIfNotFound) return null; + if (!bCreateIfNotFound) return null; PwGroup pgNew = new PwGroup(true, true, strName, PwIcon.Folder); AddGroup(pgNew, true); @@ -1167,18 +1271,18 @@ namespace KeePassLib /// Returns reference to found entry, otherwise null. public PwEntry FindEntry(PwUuid uuid, bool bSearchRecursive) { - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) { - if(pe.Uuid.Equals(uuid)) return pe; + if (pe.Uuid.Equals(uuid)) return pe; } - if(bSearchRecursive) + if (bSearchRecursive) { PwEntry peSub; - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { peSub = pg.FindEntry(uuid, true); - if(peSub != null) return peSub; + if (peSub != null) return peSub; } } @@ -1199,18 +1303,20 @@ namespace KeePassLib /// /// String that separates the group /// names. + /// Specifies whether the returned + /// path starts with the topmost group. /// Full path of the group. public string GetFullPath(string strSeparator, bool bIncludeTopMostGroup) { Debug.Assert(strSeparator != null); - if(strSeparator == null) throw new ArgumentNullException("strSeparator"); + if (strSeparator == null) throw new ArgumentNullException("strSeparator"); string strPath = m_strName; PwGroup pg = m_pParentGroup; - while(pg != null) + while (pg != null) { - if((!bIncludeTopMostGroup) && (pg.m_pParentGroup == null)) + if ((!bIncludeTopMostGroup) && (pg.m_pParentGroup == null)) break; strPath = pg.Name + strSeparator + strPath; @@ -1229,42 +1335,42 @@ namespace KeePassLib /// Recursive tree traversal. public void CreateNewItemUuids(bool bNewGroups, bool bNewEntries, bool bRecursive) { - if(bNewGroups) + if (bNewGroups) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) pg.Uuid = new PwUuid(true); } - if(bNewEntries) + if (bNewEntries) { - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) pe.SetUuid(new PwUuid(true), true); } - if(bRecursive) + if (bRecursive) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) pg.CreateNewItemUuids(bNewGroups, bNewEntries, true); } } public void TakeOwnership(bool bTakeSubGroups, bool bTakeEntries, bool bRecursive) { - if(bTakeSubGroups) + if (bTakeSubGroups) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) pg.ParentGroup = this; } - if(bTakeEntries) + if (bTakeEntries) { - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) pe.ParentGroup = this; } - if(bRecursive) + if (bRecursive) { - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) pg.TakeOwnership(bTakeSubGroups, bTakeEntries, true); } } @@ -1284,10 +1390,10 @@ namespace KeePassLib public PwGroup FindCreateSubTree(string strTree, char[] vSeparators, bool bAllowCreate) { - if(vSeparators == null) { Debug.Assert(false); vSeparators = new char[0]; } + if (vSeparators == null) { Debug.Assert(false); vSeparators = new char[0]; } string[] v = new string[vSeparators.Length]; - for(int i = 0; i < vSeparators.Length; ++i) + for (int i = 0; i < vSeparators.Length; ++i) v[i] = new string(vSeparators[i], 1); return FindCreateSubTree(strTree, v, bAllowCreate); @@ -1296,21 +1402,21 @@ namespace KeePassLib public PwGroup FindCreateSubTree(string strTree, string[] vSeparators, bool bAllowCreate) { - Debug.Assert(strTree != null); if(strTree == null) return this; - if(strTree.Length == 0) return this; + Debug.Assert(strTree != null); if (strTree == null) return this; + if (strTree.Length == 0) return this; string[] vGroups = strTree.Split(vSeparators, StringSplitOptions.None); - if((vGroups == null) || (vGroups.Length == 0)) return this; + if ((vGroups == null) || (vGroups.Length == 0)) return this; PwGroup pgContainer = this; - for(int nGroup = 0; nGroup < vGroups.Length; ++nGroup) + for (int nGroup = 0; nGroup < vGroups.Length; ++nGroup) { - if(string.IsNullOrEmpty(vGroups[nGroup])) continue; + if (string.IsNullOrEmpty(vGroups[nGroup])) continue; bool bFound = false; - foreach(PwGroup pg in pgContainer.Groups) + foreach (PwGroup pg in pgContainer.Groups) { - if(pg.Name == vGroups[nGroup]) + if (pg.Name == vGroups[nGroup]) { pgContainer = pg; bFound = true; @@ -1318,9 +1424,9 @@ namespace KeePassLib } } - if(!bFound) + if (!bFound) { - if(!bAllowCreate) return null; + if (!bAllowCreate) return null; PwGroup pg = new PwGroup(true, true, vGroups[nGroup], PwIcon.Folder); pgContainer.AddGroup(pg, true); @@ -1341,7 +1447,7 @@ namespace KeePassLib PwGroup pg = m_pParentGroup; uint uLevel = 0; - while(pg != null) + while (pg != null) { pg = pg.ParentGroup; ++uLevel; @@ -1352,10 +1458,10 @@ namespace KeePassLib public string GetAutoTypeSequenceInherited() { - if(m_strDefaultAutoTypeSequence.Length > 0) + if (m_strDefaultAutoTypeSequence.Length > 0) return m_strDefaultAutoTypeSequence; - if(m_pParentGroup != null) + if (m_pParentGroup != null) return m_pParentGroup.GetAutoTypeSequenceInherited(); return string.Empty; @@ -1363,9 +1469,9 @@ namespace KeePassLib public bool GetAutoTypeEnabledInherited() { - if(m_bEnableAutoType.HasValue) return m_bEnableAutoType.Value; + if (m_bEnableAutoType.HasValue) return m_bEnableAutoType.Value; - if(m_pParentGroup != null) + if (m_pParentGroup != null) return m_pParentGroup.GetAutoTypeEnabledInherited(); return DefaultAutoTypeEnabled; @@ -1373,9 +1479,9 @@ namespace KeePassLib public bool GetSearchingEnabledInherited() { - if(m_bEnableSearching.HasValue) return m_bEnableSearching.Value; + if (m_bEnableSearching.HasValue) return m_bEnableSearching.Value; - if(m_pParentGroup != null) + if (m_pParentGroup != null) return m_pParentGroup.GetSearchingEnabledInherited(); return DefaultSearchingEnabled; @@ -1391,10 +1497,10 @@ namespace KeePassLib /// subgroups. public PwObjectList GetGroups(bool bRecursive) { - if(bRecursive == false) return m_listGroups; + if (bRecursive == false) return m_listGroups; PwObjectList list = m_listGroups.CloneShallow(); - foreach(PwGroup pgSub in m_listGroups) + foreach (PwGroup pgSub in m_listGroups) { list.Add(pgSub.GetGroups(true)); } @@ -1404,10 +1510,10 @@ namespace KeePassLib public PwObjectList GetEntries(bool bIncludeSubGroupEntries) { - if(bIncludeSubGroupEntries == false) return m_listEntries; + if (bIncludeSubGroupEntries == false) return m_listEntries; PwObjectList list = m_listEntries.CloneShallow(); - foreach(PwGroup pgSub in m_listGroups) + foreach (PwGroup pgSub in m_listGroups) { list.Add(pgSub.GetEntries(true)); } @@ -1427,16 +1533,16 @@ namespace KeePassLib { List list = new List(); - if(!bEntries.HasValue || !bEntries.Value) + if (!bEntries.HasValue || !bEntries.Value) { PwObjectList lGroups = GetGroups(bRecursive); - foreach(PwGroup pg in lGroups) list.Add(pg); + foreach (PwGroup pg in lGroups) list.Add(pg); } - if(!bEntries.HasValue || bEntries.Value) + if (!bEntries.HasValue || bEntries.Value) { PwObjectList lEntries = GetEntries(bRecursive); - foreach(PwEntry pe in lEntries) list.Add(pe); + foreach (PwEntry pe in lEntries) list.Add(pe); } return list; @@ -1445,9 +1551,9 @@ namespace KeePassLib public bool IsContainedIn(PwGroup pgContainer) { PwGroup pgCur = m_pParentGroup; - while(pgCur != null) + while (pgCur != null) { - if(pgCur == pgContainer) return true; + if (pgCur == pgContainer) return true; pgCur = pgCur.m_pParentGroup; } @@ -1479,13 +1585,13 @@ namespace KeePassLib public void AddGroup(PwGroup subGroup, bool bTakeOwnership, bool bUpdateLocationChangedOfSub) { - if(subGroup == null) throw new ArgumentNullException("subGroup"); + if (subGroup == null) throw new ArgumentNullException("subGroup"); m_listGroups.Add(subGroup); - if(bTakeOwnership) subGroup.m_pParentGroup = this; + if (bTakeOwnership) subGroup.m_pParentGroup = this; - if(bUpdateLocationChangedOfSub) subGroup.LocationChanged = DateTime.Now; + if (bUpdateLocationChangedOfSub) subGroup.LocationChanged = DateTime.Now; } /// @@ -1512,24 +1618,24 @@ namespace KeePassLib public void AddEntry(PwEntry pe, bool bTakeOwnership, bool bUpdateLocationChangedOfEntry) { - if(pe == null) throw new ArgumentNullException("pe"); + if (pe == null) throw new ArgumentNullException("pe"); m_listEntries.Add(pe); // Do not remove the entry from its previous parent group, // only assign it to the new one - if(bTakeOwnership) pe.ParentGroup = this; + if (bTakeOwnership) pe.ParentGroup = this; - if(bUpdateLocationChangedOfEntry) pe.LocationChanged = DateTime.Now; + if (bUpdateLocationChangedOfEntry) pe.LocationChanged = DateTime.Now; } public void SortSubGroups(bool bRecursive) { m_listGroups.Sort(new PwGroupComparer()); - if(bRecursive) + if (bRecursive) { - foreach(PwGroup pgSub in m_listGroups) + foreach (PwGroup pgSub in m_listGroups) pgSub.SortSubGroups(true); } } @@ -1538,14 +1644,14 @@ namespace KeePassLib { DateTime dtNow = DateTime.Now; - foreach(PwEntry pe in m_listEntries) + foreach (PwEntry pe in m_listEntries) { PwDeletedObject pdo = new PwDeletedObject(pe.Uuid, dtNow); pdContext.DeletedObjects.Add(pdo); } m_listEntries.Clear(); - foreach(PwGroup pg in m_listGroups) + foreach (PwGroup pg in m_listGroups) { pg.DeleteAllObjects(pdContext); @@ -1555,6 +1661,68 @@ namespace KeePassLib m_listGroups.Clear(); } + internal List GetTopSearchSkippedGroups() + { + List l = new List(); + + if (!GetSearchingEnabledInherited()) l.Add(this); + else GetTopSearchSkippedGroupsRec(l); + + return l; + } + + private void GetTopSearchSkippedGroupsRec(List l) + { + if (m_bEnableSearching.HasValue && !m_bEnableSearching.Value) + { + l.Add(this); + return; + } + else { Debug.Assert(GetSearchingEnabledInherited()); } + + foreach (PwGroup pgSub in m_listGroups) + pgSub.GetTopSearchSkippedGroupsRec(l); + } + + public void SetCreatedNow(bool bRecursive) + { + DateTime dt = DateTime.Now; + + m_tCreation = dt; + m_tLastAccess = dt; + + if (!bRecursive) return; + + GroupHandler gh = delegate(PwGroup pg) + { + pg.m_tCreation = dt; + pg.m_tLastAccess = dt; + return true; + }; + + EntryHandler eh = delegate(PwEntry pe) + { + pe.CreationTime = dt; + pe.LastAccessTime = dt; + return true; + }; + + TraverseTree(TraversalMethod.PreOrder, gh, eh); + } + + public PwGroup Duplicate() + { + PwGroup pg = CloneDeep(); + + pg.Uuid = new PwUuid(true); + pg.CreateNewItemUuids(true, true, true); + + pg.SetCreatedNow(true); + + pg.TakeOwnership(true, true, true); + + return pg; + } private DateTime GetLazyTime(ref string lazyTime, ref DateTime dateTime) { if (lazyTime != null) diff --git a/src/KeePassLib2Android/PwUuid.cs b/src/KeePassLib2Android/PwUuid.cs index 801dba67..540d6164 100644 --- a/src/KeePassLib2Android/PwUuid.cs +++ b/src/KeePassLib2Android/PwUuid.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -137,12 +137,6 @@ namespace KeePassLib { if(other == null) { Debug.Assert(false); return false; } - // Shortcut - if (Object.ReferenceEquals(this, other)) - { - return true; - } - for(int i = 0; i < (int)UuidSize; ++i) { if(m_pbUuid[i] != other.m_pbUuid[i]) return false; diff --git a/src/KeePassLib2Android/Resources/KLRes.Generated.cs b/src/KeePassLib2Android/Resources/KLRes.Generated.cs index 5cfdc0ba..af6f5485 100644 --- a/src/KeePassLib2Android/Resources/KLRes.Generated.cs +++ b/src/KeePassLib2Android/Resources/KLRes.Generated.cs @@ -27,14 +27,16 @@ namespace KeePassLib.Resources if(dictNew == null) throw new ArgumentNullException("dictNew"); m_strCryptoStreamFailed = TryGetEx(dictNew, "CryptoStreamFailed", m_strCryptoStreamFailed); - m_strEncAlgorithmAes = TryGetEx(dictNew, "EncAlgorithmAes", m_strEncAlgorithmAes); + m_strEncDataTooLarge = TryGetEx(dictNew, "EncDataTooLarge", m_strEncDataTooLarge); m_strErrorInClipboard = TryGetEx(dictNew, "ErrorInClipboard", m_strErrorInClipboard); + m_strExpect100Continue = TryGetEx(dictNew, "Expect100Continue", m_strExpect100Continue); m_strFatalError = TryGetEx(dictNew, "FatalError", m_strFatalError); m_strFatalErrorText = TryGetEx(dictNew, "FatalErrorText", m_strFatalErrorText); m_strFileCorrupted = TryGetEx(dictNew, "FileCorrupted", m_strFileCorrupted); m_strFileHeaderEndEarly = TryGetEx(dictNew, "FileHeaderEndEarly", m_strFileHeaderEndEarly); m_strFileLoadFailed = TryGetEx(dictNew, "FileLoadFailed", m_strFileLoadFailed); m_strFileLockedWrite = TryGetEx(dictNew, "FileLockedWrite", m_strFileLockedWrite); + m_strFileNewVerOrPlgReq = TryGetEx(dictNew, "FileNewVerOrPlgReq", m_strFileNewVerOrPlgReq); m_strFileNewVerReq = TryGetEx(dictNew, "FileNewVerReq", m_strFileNewVerReq); m_strFileSaveCorruptionWarning = TryGetEx(dictNew, "FileSaveCorruptionWarning", m_strFileSaveCorruptionWarning); m_strFileSaveFailed = TryGetEx(dictNew, "FileSaveFailed", m_strFileSaveFailed); @@ -44,28 +46,37 @@ namespace KeePassLib.Resources m_strFileVersionUnsupported = TryGetEx(dictNew, "FileVersionUnsupported", m_strFileVersionUnsupported); m_strFinalKeyCreationFailed = TryGetEx(dictNew, "FinalKeyCreationFailed", m_strFinalKeyCreationFailed); m_strFrameworkNotImplExcp = TryGetEx(dictNew, "FrameworkNotImplExcp", m_strFrameworkNotImplExcp); + m_strGeneral = TryGetEx(dictNew, "General", m_strGeneral); m_strInvalidCompositeKey = TryGetEx(dictNew, "InvalidCompositeKey", m_strInvalidCompositeKey); m_strInvalidCompositeKeyHint = TryGetEx(dictNew, "InvalidCompositeKeyHint", m_strInvalidCompositeKeyHint); m_strInvalidDataWhileDecoding = TryGetEx(dictNew, "InvalidDataWhileDecoding", m_strInvalidDataWhileDecoding); m_strKeePass1xHint = TryGetEx(dictNew, "KeePass1xHint", m_strKeePass1xHint); + m_strKeyBits = TryGetEx(dictNew, "KeyBits", m_strKeyBits); m_strKeyFileDbSel = TryGetEx(dictNew, "KeyFileDbSel", m_strKeyFileDbSel); m_strMasterSeedLengthInvalid = TryGetEx(dictNew, "MasterSeedLengthInvalid", m_strMasterSeedLengthInvalid); m_strOldFormat = TryGetEx(dictNew, "OldFormat", m_strOldFormat); + m_strPassive = TryGetEx(dictNew, "Passive", m_strPassive); + m_strPreAuth = TryGetEx(dictNew, "PreAuth", m_strPreAuth); + m_strTimeout = TryGetEx(dictNew, "Timeout", m_strTimeout); m_strTryAgainSecs = TryGetEx(dictNew, "TryAgainSecs", m_strTryAgainSecs); m_strUnknownHeaderId = TryGetEx(dictNew, "UnknownHeaderId", m_strUnknownHeaderId); + m_strUnknownKdf = TryGetEx(dictNew, "UnknownKdf", m_strUnknownKdf); m_strUserAccountKeyError = TryGetEx(dictNew, "UserAccountKeyError", m_strUserAccountKeyError); + m_strUserAgent = TryGetEx(dictNew, "UserAgent", m_strUserAgent); } private static readonly string[] m_vKeyNames = { "CryptoStreamFailed", - "EncAlgorithmAes", + "EncDataTooLarge", "ErrorInClipboard", + "Expect100Continue", "FatalError", "FatalErrorText", "FileCorrupted", "FileHeaderEndEarly", "FileLoadFailed", "FileLockedWrite", + "FileNewVerOrPlgReq", "FileNewVerReq", "FileSaveCorruptionWarning", "FileSaveFailed", @@ -75,16 +86,23 @@ namespace KeePassLib.Resources "FileVersionUnsupported", "FinalKeyCreationFailed", "FrameworkNotImplExcp", + "General", "InvalidCompositeKey", "InvalidCompositeKeyHint", "InvalidDataWhileDecoding", "KeePass1xHint", + "KeyBits", "KeyFileDbSel", "MasterSeedLengthInvalid", "OldFormat", + "Passive", + "PreAuth", + "Timeout", "TryAgainSecs", "UnknownHeaderId", - "UserAccountKeyError" + "UnknownKdf", + "UserAccountKeyError", + "UserAgent" }; public static string[] GetKeyNames() @@ -103,15 +121,15 @@ namespace KeePassLib.Resources get { return m_strCryptoStreamFailed; } } - private static string m_strEncAlgorithmAes = - @"AES/Rijndael (256-Bit Key)"; + private static string m_strEncDataTooLarge = + @"The data is too large to be encrypted/decrypted securely using {PARAM}."; /// /// Look up a localized string similar to - /// 'AES/Rijndael (256-Bit Key)'. + /// 'The data is too large to be encrypted/decrypted securely using {PARAM}.'. /// - public static string EncAlgorithmAes + public static string EncDataTooLarge { - get { return m_strEncAlgorithmAes; } + get { return m_strEncDataTooLarge; } } private static string m_strErrorInClipboard = @@ -125,6 +143,17 @@ namespace KeePassLib.Resources get { return m_strErrorInClipboard; } } + private static string m_strExpect100Continue = + @"Expect 100-Continue responses"; + /// + /// Look up a localized string similar to + /// 'Expect 100-Continue responses'. + /// + public static string Expect100Continue + { + get { return m_strExpect100Continue; } + } + private static string m_strFatalError = @"Fatal Error"; /// @@ -191,6 +220,17 @@ namespace KeePassLib.Resources get { return m_strFileLockedWrite; } } + private static string m_strFileNewVerOrPlgReq = + @"A newer KeePass version or a plugin is required to open this file."; + /// + /// Look up a localized string similar to + /// 'A newer KeePass version or a plugin is required to open this file.'. + /// + public static string FileNewVerOrPlgReq + { + get { return m_strFileNewVerOrPlgReq; } + } + private static string m_strFileNewVerReq = @"A newer KeePass version is required to open this file."; /// @@ -290,6 +330,17 @@ namespace KeePassLib.Resources get { return m_strFrameworkNotImplExcp; } } + private static string m_strGeneral = + @"General"; + /// + /// Look up a localized string similar to + /// 'General'. + /// + public static string General + { + get { return m_strGeneral; } + } + private static string m_strInvalidCompositeKey = @"The composite key is invalid!"; /// @@ -334,6 +385,17 @@ namespace KeePassLib.Resources get { return m_strKeePass1xHint; } } + private static string m_strKeyBits = + @"{PARAM}-bit key"; + /// + /// Look up a localized string similar to + /// '{PARAM}-bit key'. + /// + public static string KeyBits + { + get { return m_strKeyBits; } + } + private static string m_strKeyFileDbSel = @"Database files cannot be used as key files."; /// @@ -367,6 +429,39 @@ namespace KeePassLib.Resources get { return m_strOldFormat; } } + private static string m_strPassive = + @"Passive"; + /// + /// Look up a localized string similar to + /// 'Passive'. + /// + public static string Passive + { + get { return m_strPassive; } + } + + private static string m_strPreAuth = + @"Pre-authenticate"; + /// + /// Look up a localized string similar to + /// 'Pre-authenticate'. + /// + public static string PreAuth + { + get { return m_strPreAuth; } + } + + private static string m_strTimeout = + @"Timeout"; + /// + /// Look up a localized string similar to + /// 'Timeout'. + /// + public static string Timeout + { + get { return m_strTimeout; } + } + private static string m_strTryAgainSecs = @"Please try it again in a few seconds."; /// @@ -389,6 +484,17 @@ namespace KeePassLib.Resources get { return m_strUnknownHeaderId; } } + private static string m_strUnknownKdf = + @"Unknown key derivation function!"; + /// + /// Look up a localized string similar to + /// 'Unknown key derivation function!'. + /// + public static string UnknownKdf + { + get { return m_strUnknownKdf; } + } + private static string m_strUserAccountKeyError = @"The operating system did not grant KeePass read/write access to the user profile folder, where the protected user key is stored."; /// @@ -399,5 +505,16 @@ namespace KeePassLib.Resources { get { return m_strUserAccountKeyError; } } + + private static string m_strUserAgent = + @"User agent"; + /// + /// Look up a localized string similar to + /// 'User agent'. + /// + public static string UserAgent + { + get { return m_strUserAgent; } + } } } diff --git a/src/KeePassLib2Android/Security/ProtectedBinary.cs b/src/KeePassLib2Android/Security/ProtectedBinary.cs index 87131f0c..8c92078f 100644 --- a/src/KeePassLib2Android/Security/ProtectedBinary.cs +++ b/src/KeePassLib2Android/Security/ProtectedBinary.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -20,10 +18,16 @@ */ using System; -using System.Security.Cryptography; using System.Diagnostics; +using System.Threading; + +#if !KeePassUAP +using System.Security.Cryptography; +#endif using KeePassLib.Cryptography; +using KeePassLib.Cryptography.Cipher; +using KeePassLib.Native; using KeePassLib.Utility; #if KeePassLibSD @@ -32,6 +36,17 @@ using KeePassLibSD; namespace KeePassLib.Security { + [Flags] + public enum PbCryptFlags + { + None = 0, + Encrypt = 1, + Decrypt = 2 + } + + public delegate void PbCryptDelegate(byte[] pbData, PbCryptFlags cf, + long lID); + /// /// Represents a protected binary, i.e. a byte array that is encrypted /// in memory. A ProtectedBinary object is immutable and @@ -39,26 +54,97 @@ namespace KeePassLib.Security /// public sealed class ProtectedBinary : IEquatable { - private const int PmBlockSize = 16; + private const int BlockSize = 16; - // In-memory protection is supported only on Windows 2000 SP3 and - // higher. - private static bool m_bProtectionSupported; + private static PbCryptDelegate g_fExtCrypt = null; + /// + /// A plugin can provide a custom memory protection method + /// by assigning a non-null delegate to this property. + /// + public static PbCryptDelegate ExtCrypt + { + get { return g_fExtCrypt; } + set { g_fExtCrypt = value; } + } + + // Local copy of the delegate that was used for encryption, + // in order to allow correct decryption even when the global + // delegate changes + private PbCryptDelegate m_fExtCrypt = null; + + private enum PbMemProt + { + None = 0, + ProtectedMemory, + ChaCha20, + ExtCrypt + } + + // ProtectedMemory is supported only on Windows 2000 SP3 and higher +#if !KeePassLibSD + private static bool? g_obProtectedMemorySupported = null; +#endif + private static bool ProtectedMemorySupported + { + get + { +#if KeePassLibSD + return false; +#else + bool? ob = g_obProtectedMemorySupported; + if(ob.HasValue) return ob.Value; + + // Mono does not implement any encryption for ProtectedMemory; + // https://sourceforge.net/p/keepass/feature-requests/1907/ + if(NativeLib.IsUnix()) + { + g_obProtectedMemorySupported = false; + return false; + } + + ob = false; + try // Test whether ProtectedMemory is supported + { + // BlockSize * 3 in order to test encryption for multiple + // blocks, but not introduce a power of 2 as factor + byte[] pb = new byte[ProtectedBinary.BlockSize * 3]; + for(int i = 0; i < pb.Length; ++i) pb[i] = (byte)i; + + throw new NotSupportedException(); + for(int i = 0; i < pb.Length; ++i) + { + if(pb[i] != (byte)i) { ob = true; break; } + } + } + catch(Exception) { } // Windows 98 / ME + + g_obProtectedMemorySupported = ob; + return ob.Value; +#endif + } + } + + private static long g_lCurID = 0; + private long m_lID; private byte[] m_pbData; // Never null - // The real length of the data. This value can be different than + // The real length of the data; this value can be different from // m_pbData.Length, as the length of m_pbData always is a multiple - // of PmBlockSize (required for fast in-memory protection). + // of BlockSize (required for ProtectedMemory) private uint m_uDataLen; - private bool m_bProtected; + private bool m_bProtected; // Protection requested by the caller + + private PbMemProt m_mp = PbMemProt.None; // Actual protection private object m_objSync = new object(); + private static byte[] g_pbKey32 = null; + /// /// A flag specifying whether the ProtectedBinary object has - /// turned on in-memory protection or not. + /// turned on memory protection or not. /// public bool IsProtected { @@ -73,19 +159,13 @@ namespace KeePassLib.Security get { return m_uDataLen; } } - static ProtectedBinary() - { - //protection not supported on Android currently - m_bProtectionSupported = false; - } - /// - /// Construct a new, empty protected binary data object. Protection - /// is disabled. + /// Construct a new, empty protected binary data object. + /// Protection is disabled. /// public ProtectedBinary() { - Init(false, new byte[0]); + Init(false, MemUtil.EmptyByteArray); } /// @@ -110,34 +190,99 @@ namespace KeePassLib.Security /// Enable protection or not. /// XorredBuffer object used to /// initialize the ProtectedBinary object. - /// Thrown if the input - /// parameter is null. public ProtectedBinary(bool bEnableProtection, XorredBuffer xbProtected) { - Debug.Assert(xbProtected != null); if(xbProtected == null) throw new ArgumentNullException("xbProtected"); + Debug.Assert(xbProtected != null); + if(xbProtected == null) throw new ArgumentNullException("xbProtected"); byte[] pb = xbProtected.ReadPlainText(); Init(bEnableProtection, pb); - MemUtil.ZeroByteArray(pb); + + if(bEnableProtection) MemUtil.ZeroByteArray(pb); } private void Init(bool bEnableProtection, byte[] pbData) { if(pbData == null) throw new ArgumentNullException("pbData"); +#if KeePassLibSD + m_lID = ++g_lCurID; +#else + m_lID = Interlocked.Increment(ref g_lCurID); +#endif + m_bProtected = bEnableProtection; m_uDataLen = (uint)pbData.Length; - int nBlocks = (int)m_uDataLen / PmBlockSize; - if((nBlocks * PmBlockSize) < (int)m_uDataLen) ++nBlocks; - Debug.Assert((nBlocks * PmBlockSize) >= (int)m_uDataLen); + const int bs = ProtectedBinary.BlockSize; + int nBlocks = (int)m_uDataLen / bs; + if((nBlocks * bs) < (int)m_uDataLen) ++nBlocks; + Debug.Assert((nBlocks * bs) >= (int)m_uDataLen); - m_pbData = new byte[nBlocks * PmBlockSize]; + m_pbData = new byte[nBlocks * bs]; Array.Copy(pbData, m_pbData, (int)m_uDataLen); - // Data size must be > 0, otherwise 'Protect' throws - if(m_bProtected && m_bProtectionSupported && (m_uDataLen > 0)) - throw new NotSupportedException(); + Encrypt(); + } + + private void Encrypt() + { + Debug.Assert(m_mp == PbMemProt.None); + + // Nothing to do if caller didn't request protection + if(!m_bProtected) return; + + // ProtectedMemory.Protect throws for data size == 0 + if(m_pbData.Length == 0) return; + + PbCryptDelegate f = g_fExtCrypt; + if(f != null) + { + f(m_pbData, PbCryptFlags.Encrypt, m_lID); + + m_fExtCrypt = f; + m_mp = PbMemProt.ExtCrypt; + return; + } + + + + byte[] pbKey32 = g_pbKey32; + if(pbKey32 == null) + { + pbKey32 = CryptoRandom.Instance.GetRandomBytes(32); + + byte[] pbUpd = Interlocked.Exchange(ref g_pbKey32, pbKey32); + if(pbUpd != null) pbKey32 = pbUpd; + } + + byte[] pbIV = new byte[12]; + MemUtil.UInt64ToBytesEx((ulong)m_lID, pbIV, 4); + using(ChaCha20Cipher c = new ChaCha20Cipher(pbKey32, pbIV, true)) + { + c.Encrypt(m_pbData, 0, m_pbData.Length); + } + m_mp = PbMemProt.ChaCha20; + } + + private void Decrypt() + { + if(m_pbData.Length == 0) return; + + else if(m_mp == PbMemProt.ChaCha20) + { + byte[] pbIV = new byte[12]; + MemUtil.UInt64ToBytesEx((ulong)m_lID, pbIV, 4); + using(ChaCha20Cipher c = new ChaCha20Cipher(g_pbKey32, pbIV, true)) + { + c.Decrypt(m_pbData, 0, m_pbData.Length); + } + } + else if(m_mp == PbMemProt.ExtCrypt) + m_fExtCrypt(m_pbData, PbCryptFlags.Decrypt, m_lID); + else { Debug.Assert(m_mp == PbMemProt.None); } + + m_mp = PbMemProt.None; } /// @@ -150,18 +295,16 @@ namespace KeePassLib.Security /// protected data and can therefore be cleared safely. public byte[] ReadData() { - if(m_uDataLen == 0) return new byte[0]; + if(m_uDataLen == 0) return MemUtil.EmptyByteArray; byte[] pbReturn = new byte[m_uDataLen]; - if(m_bProtected && m_bProtectionSupported) + lock(m_objSync) { - lock(m_objSync) - { - throw new NotSupportedException(); - } + Decrypt(); + Array.Copy(m_pbData, pbReturn, (int)m_uDataLen); + Encrypt(); } - else Array.Copy(m_pbData, pbReturn, (int)m_uDataLen); return pbReturn; } @@ -171,9 +314,6 @@ namespace KeePassLib.Security /// of bytes generated by a random stream. /// /// Random number source. - /// Protected data. - /// Thrown if the input - /// parameter is null. public byte[] ReadXorredData(CryptoRandomStream crsRandomSource) { Debug.Assert(crsRandomSource != null); @@ -183,7 +323,7 @@ namespace KeePassLib.Security uint uLen = (uint)pbData.Length; byte[] randomPad = crsRandomSource.GetRandomBytes(uLen); - Debug.Assert(randomPad.Length == uLen); + Debug.Assert(randomPad.Length == pbData.Length); for(uint i = 0; i < uLen; ++i) pbData[i] ^= randomPad[i]; @@ -191,8 +331,11 @@ namespace KeePassLib.Security return pbData; } + private int? m_hash = null; public override int GetHashCode() { + if(m_hash.HasValue) return m_hash.Value; + int h = (m_bProtected ? 0x7B11D289 : 0); byte[] pb = ReadData(); @@ -203,6 +346,7 @@ namespace KeePassLib.Security } MemUtil.ZeroByteArray(pb); + m_hash = h; return h; } diff --git a/src/KeePassLib2Android/Security/ProtectedString.cs b/src/KeePassLib2Android/Security/ProtectedString.cs index 3dd3bc4a..adad63b4 100644 --- a/src/KeePassLib2Android/Security/ProtectedString.cs +++ b/src/KeePassLib2Android/Security/ProtectedString.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,8 +18,8 @@ */ using System; -using System.Text; using System.Diagnostics; +using System.Text; using KeePassLib.Cryptography; using KeePassLib.Utility; @@ -47,7 +47,7 @@ namespace KeePassLib.Security private bool m_bIsProtected; - private static ProtectedString m_psEmpty = new ProtectedString(); + private static readonly ProtectedString m_psEmpty = new ProtectedString(); public static ProtectedString Empty { get { return m_psEmpty; } @@ -55,7 +55,7 @@ namespace KeePassLib.Security /// /// A flag specifying whether the ProtectedString object - /// has turned on in-memory protection or not. + /// has turned on memory protection or not. /// public bool IsProtected { @@ -112,10 +112,9 @@ namespace KeePassLib.Security /// to the value supplied in the parameters. /// /// If this parameter is true, - /// the string will be protected in-memory (encrypted). If it + /// the string will be protected in memory (encrypted). If it /// is false, the string will be stored as plain-text. - /// The initial string value. This - /// parameter won't be modified. + /// The initial string value. public ProtectedString(bool bEnableProtection, string strValue) { Init(bEnableProtection, strValue); @@ -126,7 +125,7 @@ namespace KeePassLib.Security /// to the value supplied in the parameters (UTF-8 encoded string). /// /// If this parameter is true, - /// the string will be protected in-memory (encrypted). If it + /// the string will be protected in memory (encrypted). If it /// is false, the string will be stored as plain-text. /// The initial string value, encoded as /// UTF-8 byte array. This parameter won't be modified; the caller @@ -144,15 +143,15 @@ namespace KeePassLib.Security /// XorredBuffer object containing the /// string in UTF-8 representation. The UTF-8 string must not /// be null-terminated. - /// Thrown if the input - /// parameter is null. public ProtectedString(bool bEnableProtection, XorredBuffer xbProtected) { + Debug.Assert(xbProtected != null); if(xbProtected == null) throw new ArgumentNullException("xbProtected"); byte[] pb = xbProtected.ReadPlainText(); Init(bEnableProtection, pb); - MemUtil.ZeroByteArray(pb); + + if(bEnableProtection) MemUtil.ZeroByteArray(pb); } private void Init(bool bEnableProtection, string str) @@ -222,8 +221,6 @@ namespace KeePassLib.Security /// /// Random number source. /// Protected string. - /// Thrown if the input - /// parameter is null. public byte[] ReadXorredString(CryptoRandomStream crsRandomSource) { Debug.Assert(crsRandomSource != null); if(crsRandomSource == null) throw new ArgumentNullException("crsRandomSource"); @@ -232,7 +229,7 @@ namespace KeePassLib.Security uint uLen = (uint)pbData.Length; byte[] randomPad = crsRandomSource.GetRandomBytes(uLen); - Debug.Assert(randomPad.Length == uLen); + Debug.Assert(randomPad.Length == pbData.Length); for(uint i = 0; i < uLen; ++i) pbData[i] ^= randomPad[i]; @@ -246,7 +243,103 @@ namespace KeePassLib.Security byte[] pb = ReadUtf8(); ProtectedString ps = new ProtectedString(bProtect, pb); - MemUtil.ZeroByteArray(pb); + + if(bProtect) MemUtil.ZeroByteArray(pb); + return ps; + } + + public ProtectedString Insert(int iStart, string strInsert) + { + if(iStart < 0) throw new ArgumentOutOfRangeException("iStart"); + if(strInsert == null) throw new ArgumentNullException("strInsert"); + if(strInsert.Length == 0) return this; + + // Only operate directly with strings when m_bIsProtected is + // false, not in the case of non-null m_strPlainText, because + // the operation creates a new sequence in memory + if(!m_bIsProtected) + return new ProtectedString(false, ReadString().Insert( + iStart, strInsert)); + + UTF8Encoding utf8 = StrUtil.Utf8; + + byte[] pb = ReadUtf8(); + char[] v = utf8.GetChars(pb); + char[] vNew; + + try + { + if(iStart > v.Length) + throw new ArgumentOutOfRangeException("iStart"); + + char[] vIns = strInsert.ToCharArray(); + + vNew = new char[v.Length + vIns.Length]; + Array.Copy(v, 0, vNew, 0, iStart); + Array.Copy(vIns, 0, vNew, iStart, vIns.Length); + Array.Copy(v, iStart, vNew, iStart + vIns.Length, + v.Length - iStart); + } + finally + { + Array.Clear(v, 0, v.Length); + MemUtil.ZeroByteArray(pb); + } + + byte[] pbNew = utf8.GetBytes(vNew); + ProtectedString ps = new ProtectedString(m_bIsProtected, pbNew); + + Debug.Assert(utf8.GetString(pbNew, 0, pbNew.Length) == + ReadString().Insert(iStart, strInsert)); + + Array.Clear(vNew, 0, vNew.Length); + MemUtil.ZeroByteArray(pbNew); + return ps; + } + + public ProtectedString Remove(int iStart, int nCount) + { + if(iStart < 0) throw new ArgumentOutOfRangeException("iStart"); + if(nCount < 0) throw new ArgumentOutOfRangeException("nCount"); + if(nCount == 0) return this; + + // Only operate directly with strings when m_bIsProtected is + // false, not in the case of non-null m_strPlainText, because + // the operation creates a new sequence in memory + if(!m_bIsProtected) + return new ProtectedString(false, ReadString().Remove( + iStart, nCount)); + + UTF8Encoding utf8 = StrUtil.Utf8; + + byte[] pb = ReadUtf8(); + char[] v = utf8.GetChars(pb); + char[] vNew; + + try + { + if((iStart + nCount) > v.Length) + throw new ArgumentException("iStart + nCount"); + + vNew = new char[v.Length - nCount]; + Array.Copy(v, 0, vNew, 0, iStart); + Array.Copy(v, iStart + nCount, vNew, iStart, v.Length - + (iStart + nCount)); + } + finally + { + Array.Clear(v, 0, v.Length); + MemUtil.ZeroByteArray(pb); + } + + byte[] pbNew = utf8.GetBytes(vNew); + ProtectedString ps = new ProtectedString(m_bIsProtected, pbNew); + + Debug.Assert(utf8.GetString(pbNew, 0, pbNew.Length) == + ReadString().Remove(iStart, nCount)); + + Array.Clear(vNew, 0, vNew.Length); + MemUtil.ZeroByteArray(pbNew); return ps; } } diff --git a/src/KeePassLib2Android/Security/XorredBuffer.cs b/src/KeePassLib2Android/Security/XorredBuffer.cs index 7afa2d9b..8586f295 100644 --- a/src/KeePassLib2Android/Security/XorredBuffer.cs +++ b/src/KeePassLib2Android/Security/XorredBuffer.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Serialization/BinaryReaderEx.cs b/src/KeePassLib2Android/Serialization/BinaryReaderEx.cs index 12bf7623..9d4351fd 100644 --- a/src/KeePassLib2Android/Serialization/BinaryReaderEx.cs +++ b/src/KeePassLib2Android/Serialization/BinaryReaderEx.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,8 +19,8 @@ using System; using System.Collections.Generic; -using System.Text; using System.IO; +using System.Text; using KeePassLib.Utility; diff --git a/src/KeePassLib2Android/Serialization/FileLock.cs b/src/KeePassLib2Android/Serialization/FileLock.cs index b58bb653..7cc591a0 100644 --- a/src/KeePassLib2Android/Serialization/FileLock.cs +++ b/src/KeePassLib2Android/Serialization/FileLock.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,10 +19,10 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Threading; using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; using KeePassLib.Cryptography; using KeePassLib.Resources; @@ -139,7 +137,7 @@ namespace KeePassLib.Serialization if(!v[0].StartsWith(LockFileHeader)) { Debug.Assert(false); return null; } return new LockFileInfo(v[1], v[2], v[3], v[4], v[5]); } - catch(Java.IO.FileNotFoundException) { } + catch(FileNotFoundException) { } catch(Exception) { Debug.Assert(false); } finally { if(s != null) s.Close(); } @@ -154,15 +152,17 @@ namespace KeePassLib.Serialization try { byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16); - string strTime = TimeUtil.SerializeUtc(DateTime.Now); + string strTime = TimeUtil.SerializeUtc(DateTime.UtcNow); -#if (!KeePassLibSD && !KeePassRT) lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime, +#if KeePassUAP + EnvironmentExt.UserName, EnvironmentExt.MachineName, + EnvironmentExt.UserDomainName); +#elif KeePassLibSD + string.Empty, string.Empty, string.Empty); +#else Environment.UserName, Environment.MachineName, Environment.UserDomainName); -#else - lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime, - string.Empty, string.Empty, string.Empty); #endif StringBuilder sb = new StringBuilder(); @@ -244,8 +244,8 @@ namespace KeePassLib.Serialization if(bDisposing) Thread.Sleep(50); } - if(bDisposing && !bFileDeleted) - IOConnection.DeleteFile(m_iocLockFile); // Possibly with exception + // if(bDisposing && !bFileDeleted) + // IOConnection.DeleteFile(m_iocLockFile); // Possibly with exception m_iocLockFile = null; } diff --git a/src/KeePassLib2Android/Serialization/FileTransactionEx.cs b/src/KeePassLib2Android/Serialization/FileTransactionEx.cs index 2265d198..f93360d8 100644 --- a/src/KeePassLib2Android/Serialization/FileTransactionEx.cs +++ b/src/KeePassLib2Android/Serialization/FileTransactionEx.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll @@ -21,11 +21,11 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; using System.Diagnostics; +using System.IO; +using System.Text; -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) using System.Security.AccessControl; #endif @@ -44,6 +44,9 @@ namespace KeePassLib.Serialization private const string StrTempSuffix = ".tmp"; + private static Dictionary g_dEnabled = + new Dictionary(StrUtil.CaseIgnoreComparer); + public FileTransactionEx(IOConnectionInfo iocBaseFile) { Initialize(iocBaseFile, true); @@ -101,7 +104,7 @@ namespace KeePassLib.Serialization { bool bMadeUnhidden = UrlUtil.UnhideFile(m_iocBase.Path); -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) bool bEfsEncrypted = false; #endif @@ -130,7 +133,7 @@ namespace KeePassLib.Serialization IOConnection.RenameFile(m_iocTemp, m_iocBase); -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) if(m_iocBase.IsLocalFile()) { try @@ -148,5 +151,15 @@ namespace KeePassLib.Serialization if(bMadeUnhidden) UrlUtil.HideFile(m_iocBase.Path, true); // Hide again } + + // For plugins + public static void Configure(string strPrefix, bool? obTransacted) + { + if(string.IsNullOrEmpty(strPrefix)) { Debug.Assert(false); return; } + + if(obTransacted.HasValue) + g_dEnabled[strPrefix] = obTransacted.Value; + else g_dEnabled.Remove(strPrefix); } } +} diff --git a/src/KeePassLib2Android/Serialization/HashedBlockStream.cs b/src/KeePassLib2Android/Serialization/HashedBlockStream.cs index 8c488a0c..dd2955b9 100644 --- a/src/KeePassLib2Android/Serialization/HashedBlockStream.cs +++ b/src/KeePassLib2Android/Serialization/HashedBlockStream.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll @@ -20,11 +20,11 @@ */ using System; -using System.IO; -using System.Security.Cryptography; using System.Diagnostics; +using System.IO; using System.Text; +using KeePassLib.Cryptography; using KeePassLib.Native; using KeePassLib.Utility; @@ -74,7 +74,7 @@ namespace KeePassLib.Serialization public sealed class HashedBlockStream : Stream { - private const int m_nDefaultBufferSize = 1024 * 1024; // 1 MB + private const int NbDefaultBufferSize = 1024 * 1024; // 1 MB private Stream m_sBaseStream; private bool m_bWriting; @@ -87,7 +87,7 @@ namespace KeePassLib.Serialization private byte[] m_pbBuffer; private int m_nBufferPos = 0; - private uint m_uBufferIndex = 0; + private uint m_uBlockIndex = 0; public override bool CanRead { @@ -106,13 +106,13 @@ namespace KeePassLib.Serialization public override long Length { - get { throw new NotSupportedException(); } + get { Debug.Assert(false); throw new NotSupportedException(); } } public override long Position { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } + get { Debug.Assert(false); throw new NotSupportedException(); } + set { Debug.Assert(false); throw new NotSupportedException(); } } public HashedBlockStream(Stream sBaseStream, bool bWriting) @@ -137,25 +137,25 @@ namespace KeePassLib.Serialization if(sBaseStream == null) throw new ArgumentNullException("sBaseStream"); if(nBufferSize < 0) throw new ArgumentOutOfRangeException("nBufferSize"); - if(nBufferSize == 0) nBufferSize = m_nDefaultBufferSize; + if(nBufferSize == 0) nBufferSize = NbDefaultBufferSize; m_sBaseStream = sBaseStream; m_bWriting = bWriting; m_bVerify = bVerify; UTF8Encoding utf8 = StrUtil.Utf8; - if(m_bWriting == false) // Reading mode + if(!m_bWriting) // Reading mode { - if(m_sBaseStream.CanRead == false) + if(!m_sBaseStream.CanRead) throw new InvalidOperationException(); m_brInput = new BinaryReader(sBaseStream, utf8); - m_pbBuffer = new byte[0]; + m_pbBuffer = MemUtil.EmptyByteArray; } else // Writing mode { - if(m_sBaseStream.CanWrite == false) + if(!m_sBaseStream.CanWrite) throw new InvalidOperationException(); m_bwOutput = new BinaryWriter(sBaseStream, utf8); @@ -169,7 +169,7 @@ namespace KeePassLib.Serialization if(m_bWriting) m_bwOutput.Flush(); } -#if KeePassRT +#if KeePassUAP protected override void Dispose(bool disposing) { if(!disposing) return; @@ -179,7 +179,7 @@ namespace KeePassLib.Serialization #endif if(m_sBaseStream != null) { - if(m_bWriting == false) // Reading mode + if(!m_bWriting) // Reading mode { m_brInput.Close(); m_brInput = null; @@ -224,7 +224,7 @@ namespace KeePassLib.Serialization if(m_nBufferPos == m_pbBuffer.Length) { if(ReadHashedBlock() == false) - return nCount - nRemaining; // Bytes actually read + return (nCount - nRemaining); // Bytes actually read } int nCopy = Math.Min(m_pbBuffer.Length - m_nBufferPos, nRemaining); @@ -246,9 +246,9 @@ namespace KeePassLib.Serialization m_nBufferPos = 0; - if(m_brInput.ReadUInt32() != m_uBufferIndex) + if(m_brInput.ReadUInt32() != m_uBlockIndex) throw new InvalidDataException(); - ++m_uBufferIndex; + ++m_uBlockIndex; byte[] pbStoredHash = m_brInput.ReadBytes(32); if((pbStoredHash == null) || (pbStoredHash.Length != 32)) @@ -273,7 +273,7 @@ namespace KeePassLib.Serialization } m_bEos = true; - m_pbBuffer = new byte[0]; + m_pbBuffer = MemUtil.EmptyByteArray; return false; } @@ -283,17 +283,13 @@ namespace KeePassLib.Serialization if(m_bVerify) { - SHA256Managed sha256 = new SHA256Managed(); - byte[] pbComputedHash = sha256.ComputeHash(m_pbBuffer); + byte[] pbComputedHash = CryptoUtil.HashSha256(m_pbBuffer); if((pbComputedHash == null) || (pbComputedHash.Length != 32)) throw new InvalidOperationException(); - for(int iHashPos = 0; iHashPos < 32; ++iHashPos) - { - if(pbStoredHash[iHashPos] != pbComputedHash[iHashPos]) + if(!MemUtil.ArraysEqual(pbStoredHash, pbComputedHash)) throw new InvalidDataException(); } - } return true; } @@ -320,26 +316,24 @@ namespace KeePassLib.Serialization private void WriteHashedBlock() { - m_bwOutput.Write(m_uBufferIndex); - ++m_uBufferIndex; + m_bwOutput.Write(m_uBlockIndex); + ++m_uBlockIndex; if(m_nBufferPos > 0) { - SHA256Managed sha256 = new SHA256Managed(); + byte[] pbHash = CryptoUtil.HashSha256(m_pbBuffer, 0, m_nBufferPos); -#if !KeePassLibSD - byte[] pbHash = sha256.ComputeHash(m_pbBuffer, 0, m_nBufferPos); -#else - byte[] pbHash; - if(m_nBufferPos == m_pbBuffer.Length) - pbHash = sha256.ComputeHash(m_pbBuffer); - else - { - byte[] pbData = new byte[m_nBufferPos]; - Array.Copy(m_pbBuffer, 0, pbData, 0, m_nBufferPos); - pbHash = sha256.ComputeHash(pbData); - } -#endif + + // SHA256Managed sha256 = new SHA256Managed(); + // byte[] pbHash; + // if(m_nBufferPos == m_pbBuffer.Length) + // pbHash = sha256.ComputeHash(m_pbBuffer); + // else + // { + // byte[] pbData = new byte[m_nBufferPos]; + // Array.Copy(m_pbBuffer, 0, pbData, 0, m_nBufferPos); + // pbHash = sha256.ComputeHash(pbData); + // } m_bwOutput.Write(pbHash); } diff --git a/src/KeePassLib2Android/Serialization/HmacBlockStream.cs b/src/KeePassLib2Android/Serialization/HmacBlockStream.cs new file mode 100644 index 00000000..59295742 --- /dev/null +++ b/src/KeePassLib2Android/Serialization/HmacBlockStream.cs @@ -0,0 +1,325 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; + +#if !KeePassUAP +using System.Security.Cryptography; +#endif + +using KeePassLib.Resources; +using KeePassLib.Utility; + +namespace KeePassLib.Serialization +{ + public sealed class HmacBlockStream : Stream + { + private const int NbDefaultBufferSize = 1024 * 1024; // 1 MB + + private Stream m_sBase; + private readonly bool m_bWriting; + private readonly bool m_bVerify; + private byte[] m_pbKey; + + private bool m_bEos = false; + private byte[] m_pbBuffer; + private int m_iBufferPos = 0; + + private ulong m_uBlockIndex = 0; + + public override bool CanRead + { + get { return !m_bWriting; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return m_bWriting; } + } + + public override long Length + { + get { Debug.Assert(false); throw new NotSupportedException(); } + } + + public override long Position + { + get { Debug.Assert(false); throw new NotSupportedException(); } + set { Debug.Assert(false); throw new NotSupportedException(); } + } + + public HmacBlockStream(Stream sBase, bool bWriting, bool bVerify, + byte[] pbKey) + { + if(sBase == null) throw new ArgumentNullException("sBase"); + if(pbKey == null) throw new ArgumentNullException("pbKey"); + + m_sBase = sBase; + m_bWriting = bWriting; + m_bVerify = bVerify; + m_pbKey = pbKey; + + if(!m_bWriting) // Reading mode + { + if(!m_sBase.CanRead) throw new InvalidOperationException(); + + m_pbBuffer = MemUtil.EmptyByteArray; + } + else // Writing mode + { + if(!m_sBase.CanWrite) throw new InvalidOperationException(); + + m_pbBuffer = new byte[NbDefaultBufferSize]; + } + } + + public override void Flush() + { + Debug.Assert(m_sBase != null); // Object should not be disposed + if(m_bWriting && (m_sBase != null)) m_sBase.Flush(); + } + +#if KeePassUAP + protected override void Dispose(bool disposing) + { + if(!disposing) return; +#else + public override void Close() + { +#endif + if(m_sBase != null) + { + if(m_bWriting) + { + if(m_iBufferPos == 0) // No data left in buffer + WriteSafeBlock(); // Write terminating block + else + { + WriteSafeBlock(); // Write remaining buffered data + WriteSafeBlock(); // Write terminating block + } + + Flush(); + } + + m_sBase.Close(); + m_sBase = null; + } + } + + public override long Seek(long lOffset, SeekOrigin soOrigin) + { + Debug.Assert(false); + throw new NotSupportedException(); + } + + public override void SetLength(long lValue) + { + Debug.Assert(false); + throw new NotSupportedException(); + } + + internal static byte[] GetHmacKey64(byte[] pbKey, ulong uBlockIndex) + { + if(pbKey == null) throw new ArgumentNullException("pbKey"); + Debug.Assert(pbKey.Length == 64); + + // We are computing the HMAC using SHA-256, whose internal + // block size is 512 bits; thus create a key that is 512 + // bits long (using SHA-512) + + byte[] pbBlockKey; + using(SHA512Managed h = new SHA512Managed()) + { + byte[] pbIndex = MemUtil.UInt64ToBytes(uBlockIndex); + + h.TransformBlock(pbIndex, 0, pbIndex.Length, pbIndex, 0); + h.TransformBlock(pbKey, 0, pbKey.Length, pbKey, 0); + h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + + pbBlockKey = h.Hash; + } + +#if DEBUG + byte[] pbZero = new byte[64]; + Debug.Assert((pbBlockKey.Length == 64) && !MemUtil.ArraysEqual( + pbBlockKey, pbZero)); // Ensure we own pbBlockKey +#endif + return pbBlockKey; + } + + public override int Read(byte[] pbBuffer, int iOffset, int nCount) + { + if(m_bWriting) throw new InvalidOperationException(); + + int nRemaining = nCount; + while(nRemaining > 0) + { + if(m_iBufferPos == m_pbBuffer.Length) + { + if(!ReadSafeBlock()) + return (nCount - nRemaining); // Bytes actually read + } + + int nCopy = Math.Min(m_pbBuffer.Length - m_iBufferPos, nRemaining); + Debug.Assert(nCopy > 0); + + Array.Copy(m_pbBuffer, m_iBufferPos, pbBuffer, iOffset, nCopy); + + iOffset += nCopy; + m_iBufferPos += nCopy; + + nRemaining -= nCopy; + } + + return nCount; + } + + private bool ReadSafeBlock() + { + if(m_bEos) return false; // End of stream reached already + + byte[] pbStoredHmac = MemUtil.Read(m_sBase, 32); + if((pbStoredHmac == null) || (pbStoredHmac.Length != 32)) + throw new EndOfStreamException(); + + // Block index is implicit: it's used in the HMAC computation, + // but does not need to be stored + // byte[] pbBlockIndex = MemUtil.Read(m_sBase, 8); + // if((pbBlockIndex == null) || (pbBlockIndex.Length != 8)) + // throw new EndOfStreamException(); + // ulong uBlockIndex = MemUtil.BytesToUInt64(pbBlockIndex); + // if((uBlockIndex != m_uBlockIndex) && m_bVerify) + // throw new InvalidDataException(); + byte[] pbBlockIndex = MemUtil.UInt64ToBytes(m_uBlockIndex); + + byte[] pbBlockSize = MemUtil.Read(m_sBase, 4); + if((pbBlockSize == null) || (pbBlockSize.Length != 4)) + throw new EndOfStreamException(); + int nBlockSize = MemUtil.BytesToInt32(pbBlockSize); + if(nBlockSize < 0) + throw new InvalidDataException(KLRes.FileCorrupted); + + m_iBufferPos = 0; + + m_pbBuffer = MemUtil.Read(m_sBase, nBlockSize); + if((m_pbBuffer == null) || ((m_pbBuffer.Length != nBlockSize) && m_bVerify)) + throw new EndOfStreamException(); + + if(m_bVerify) + { + byte[] pbCmpHmac; + byte[] pbBlockKey = GetHmacKey64(m_pbKey, m_uBlockIndex); + using(HMACSHA256 h = new HMACSHA256(pbBlockKey)) + { + h.TransformBlock(pbBlockIndex, 0, pbBlockIndex.Length, + pbBlockIndex, 0); + h.TransformBlock(pbBlockSize, 0, pbBlockSize.Length, + pbBlockSize, 0); + + if(m_pbBuffer.Length > 0) + h.TransformBlock(m_pbBuffer, 0, m_pbBuffer.Length, + m_pbBuffer, 0); + + h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + + pbCmpHmac = h.Hash; + } + MemUtil.ZeroByteArray(pbBlockKey); + + if(!MemUtil.ArraysEqual(pbCmpHmac, pbStoredHmac)) + throw new InvalidDataException(KLRes.FileCorrupted); + } + + ++m_uBlockIndex; + + if(nBlockSize == 0) + { + m_bEos = true; + return false; // No further data available + } + return true; + } + + public override void Write(byte[] pbBuffer, int iOffset, int nCount) + { + if(!m_bWriting) throw new InvalidOperationException(); + + while(nCount > 0) + { + if(m_iBufferPos == m_pbBuffer.Length) + WriteSafeBlock(); + + int nCopy = Math.Min(m_pbBuffer.Length - m_iBufferPos, nCount); + Debug.Assert(nCopy > 0); + + Array.Copy(pbBuffer, iOffset, m_pbBuffer, m_iBufferPos, nCopy); + + iOffset += nCopy; + m_iBufferPos += nCopy; + + nCount -= nCopy; + } + } + + private void WriteSafeBlock() + { + byte[] pbBlockIndex = MemUtil.UInt64ToBytes(m_uBlockIndex); + + int cbBlockSize = m_iBufferPos; + byte[] pbBlockSize = MemUtil.Int32ToBytes(cbBlockSize); + + byte[] pbBlockHmac; + byte[] pbBlockKey = GetHmacKey64(m_pbKey, m_uBlockIndex); + using(HMACSHA256 h = new HMACSHA256(pbBlockKey)) + { + h.TransformBlock(pbBlockIndex, 0, pbBlockIndex.Length, + pbBlockIndex, 0); + h.TransformBlock(pbBlockSize, 0, pbBlockSize.Length, + pbBlockSize, 0); + + if(cbBlockSize > 0) + h.TransformBlock(m_pbBuffer, 0, cbBlockSize, m_pbBuffer, 0); + + h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); + + pbBlockHmac = h.Hash; + } + MemUtil.ZeroByteArray(pbBlockKey); + + MemUtil.Write(m_sBase, pbBlockHmac); + // MemUtil.Write(m_sBase, pbBlockIndex); // Implicit + MemUtil.Write(m_sBase, pbBlockSize); + if(cbBlockSize > 0) + m_sBase.Write(m_pbBuffer, 0, cbBlockSize); + + ++m_uBlockIndex; + m_iBufferPos = 0; + } + } +} diff --git a/src/KeePassLib2Android/Serialization/IOConnectionInfo.cs b/src/KeePassLib2Android/Serialization/IOConnectionInfo.cs index d73f2c5a..a692d94f 100644 --- a/src/KeePassLib2Android/Serialization/IOConnectionInfo.cs +++ b/src/KeePassLib2Android/Serialization/IOConnectionInfo.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,12 +19,11 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Net; using System.ComponentModel; -using System.Xml.Serialization; using System.Diagnostics; +using System.IO; +using System.Text; +using System.Xml.Serialization; using KeePassLib.Interfaces; using KeePassLib.Utility; @@ -122,7 +121,7 @@ namespace KeePassLib.Serialization private bool m_bComplete = false; [XmlIgnore] - internal bool IsComplete // Credentials etc. fully specified + public bool IsComplete // Credentials etc. fully specified { get { return m_bComplete; } set { m_bComplete = value; } @@ -134,16 +133,53 @@ namespace KeePassLib.Serialization set { m_ioHint = value; } } */ - public IOConnectionInfo CloneDeep() + private IocProperties m_props = new IocProperties(); + [XmlIgnore] + public IocProperties Properties { - return (IOConnectionInfo)this.MemberwiseClone(); + get { return m_props; } + set + { + if(value == null) throw new ArgumentNullException("value"); + m_props = value; + } } + /// + /// For serialization only; use Properties in code. + /// + [DefaultValue("")] + public string PropertiesEx + { + get { return m_props.Serialize(); } + set + { + if(value == null) throw new ArgumentNullException("value"); + IocProperties p = IocProperties.Deserialize(value); + Debug.Assert(p != null); + m_props = (p ?? new IocProperties()); + } + } + + public IOConnectionInfo CloneDeep() + { + IOConnectionInfo ioc = (IOConnectionInfo)this.MemberwiseClone(); + ioc.m_props = m_props.CloneDeep(); + return ioc; + } + +#if DEBUG // For debugger display only + public override string ToString() + { + return GetDisplayName(); + } +#endif + + /// /// Serialize the current connection info to a string. Credentials - /// are only serialized if the SaveCredentials property - /// is true. + /// are serialized based on the CredSaveMode property. /// /// Input object to be serialized. /// Serialized object as string. @@ -215,9 +251,8 @@ namespace KeePassLib.Serialization s.Password = TransformUnreadable(vParts[3], false); return s; } - - - + + /// /// Very simple string protection. Doesn't really encrypt the input /// string, only encodes it that it's not readable on the first glance. @@ -256,21 +291,21 @@ namespace KeePassLib.Serialization return StrUtil.Utf8.GetString(pbBase, 0, pbBase.Length); } } - + public string GetDisplayName() { string str = m_strUrl; if(m_strUser.Length > 0) - str += " (" + m_strUser + ")"; + str += (" (" + m_strUser + ")"); return str; } public bool IsEmpty() { - return (m_strUrl.Length > 0); + return (m_strUrl.Length == 0); } public static IOConnectionInfo FromPath(string strPath) @@ -293,7 +328,7 @@ namespace KeePassLib.Serialization public bool IsLocalFile() { // Not just ":/", see e.g. AppConfigEx.ChangePathRelAbs - return (m_strUrl.IndexOf(@"://") < 0); + return (m_strUrl.IndexOf("://") < 0); } public void ClearCredentials(bool bDependingOnRememberMode) diff --git a/src/KeePassLib2Android/Serialization/IocProperties.cs b/src/KeePassLib2Android/Serialization/IocProperties.cs new file mode 100644 index 00000000..9fd9acc6 --- /dev/null +++ b/src/KeePassLib2Android/Serialization/IocProperties.cs @@ -0,0 +1,192 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Xml; + +using KeePassLib.Interfaces; +using KeePassLib.Utility; + +using StrDict = System.Collections.Generic.Dictionary; + +namespace KeePassLib.Serialization +{ + public interface IHasIocProperties + { + IocProperties IOConnectionProperties { get; set; } + } + + public sealed class IocProperties : IDeepCloneable + { + private StrDict m_dict = new StrDict(); + + public IocProperties() + { + } + + public IocProperties CloneDeep() + { + IocProperties p = new IocProperties(); + p.m_dict = new StrDict(m_dict); + return p; + } + + public string Get(string strKey) + { + if(string.IsNullOrEmpty(strKey)) return null; + + foreach(KeyValuePair kvp in m_dict) + { + if(kvp.Key.Equals(strKey, StrUtil.CaseIgnoreCmp)) + return kvp.Value; + } + + return null; + } + + public void Set(string strKey, string strValue) + { + if(string.IsNullOrEmpty(strKey)) { Debug.Assert(false); return; } + + foreach(KeyValuePair kvp in m_dict) + { + if(kvp.Key.Equals(strKey, StrUtil.CaseIgnoreCmp)) + { + if(string.IsNullOrEmpty(strValue)) m_dict.Remove(kvp.Key); + else m_dict[kvp.Key] = strValue; + return; + } + } + + if(!string.IsNullOrEmpty(strValue)) m_dict[strKey] = strValue; + } + + public bool? GetBool(string strKey) + { + string str = Get(strKey); + if(string.IsNullOrEmpty(str)) return null; + + return StrUtil.StringToBool(str); + } + + public void SetBool(string strKey, bool? ob) + { + if(ob.HasValue) Set(strKey, (ob.Value ? "1" : "0")); + else Set(strKey, null); + } + + public long? GetLong(string strKey) + { + string str = Get(strKey); + if(string.IsNullOrEmpty(str)) return null; + + long l; + if(StrUtil.TryParseLongInvariant(str, out l)) return l; + Debug.Assert(false); + return null; + } + + public void SetLong(string strKey, long? ol) + { + if(ol.HasValue) + Set(strKey, ol.Value.ToString(NumberFormatInfo.InvariantInfo)); + else Set(strKey, null); + } + + public string Serialize() + { + if(m_dict.Count == 0) return string.Empty; + + StringBuilder sbAll = new StringBuilder(); + foreach(KeyValuePair kvp in m_dict) + { + sbAll.Append(kvp.Key); + sbAll.Append(kvp.Value); + } + + string strAll = sbAll.ToString(); + char chSepOuter = ';'; + if(strAll.IndexOf(chSepOuter) >= 0) + chSepOuter = StrUtil.GetUnusedChar(strAll); + + strAll += chSepOuter; + char chSepInner = '='; + if(strAll.IndexOf(chSepInner) >= 0) + chSepInner = StrUtil.GetUnusedChar(strAll); + + StringBuilder sb = new StringBuilder(); + sb.Append(chSepOuter); + sb.Append(chSepInner); + + foreach(KeyValuePair kvp in m_dict) + { + sb.Append(chSepOuter); + sb.Append(kvp.Key); + sb.Append(chSepInner); + sb.Append(kvp.Value); + } + + return sb.ToString(); + } + + public static IocProperties Deserialize(string strSerialized) + { + IocProperties p = new IocProperties(); + if(string.IsNullOrEmpty(strSerialized)) return p; // No assert + + char chSepOuter = strSerialized[0]; + string[] v = strSerialized.Substring(1).Split(new char[] { chSepOuter }); + if((v == null) || (v.Length < 2)) { Debug.Assert(false); return p; } + + string strMeta = v[0]; + if(string.IsNullOrEmpty(strMeta)) { Debug.Assert(false); return p; } + + char chSepInner = strMeta[0]; + char[] vSepInner = new char[] { chSepInner }; + + for(int i = 1; i < v.Length; ++i) + { + string strProp = v[i]; + if(string.IsNullOrEmpty(strProp)) { Debug.Assert(false); continue; } + + string[] vProp = strProp.Split(vSepInner); + if((vProp == null) || (vProp.Length < 2)) { Debug.Assert(false); continue; } + Debug.Assert(vProp.Length == 2); + + p.Set(vProp[0], vProp[1]); + } + + return p; + } + + public void CopyTo(IocProperties p) + { + if(p == null) { Debug.Assert(false); return; } + + foreach(KeyValuePair kvp in m_dict) + { + p.m_dict[kvp.Key] = kvp.Value; + } + } + } +} diff --git a/src/KeePassLib2Android/Serialization/IocPropertyInfo.cs b/src/KeePassLib2Android/Serialization/IocPropertyInfo.cs new file mode 100644 index 00000000..c63358f4 --- /dev/null +++ b/src/KeePassLib2Android/Serialization/IocPropertyInfo.cs @@ -0,0 +1,99 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +using KeePassLib.Utility; + +namespace KeePassLib.Serialization +{ + public sealed class IocPropertyInfo + { + private readonly string m_strName; + public string Name + { + get { return m_strName; } + } + + private readonly Type m_t; + public Type Type + { + get { return m_t; } + } + + private string m_strDisplayName; + public string DisplayName + { + get { return m_strDisplayName; } + set + { + if(value == null) throw new ArgumentNullException("value"); + m_strDisplayName = value; + } + } + + private List m_lProtocols = new List(); + public IEnumerable Protocols + { + get { return m_lProtocols; } + } + + public IocPropertyInfo(string strName, Type t, string strDisplayName, + string[] vProtocols) + { + if(strName == null) throw new ArgumentNullException("strName"); + if(t == null) throw new ArgumentNullException("t"); + if(strDisplayName == null) throw new ArgumentNullException("strDisplayName"); + + m_strName = strName; + m_t = t; + m_strDisplayName = strDisplayName; + + AddProtocols(vProtocols); + } + + public void AddProtocols(string[] v) + { + if(v == null) { Debug.Assert(false); return; } + + foreach(string strProtocol in v) + { + if(strProtocol == null) continue; + + string str = strProtocol.Trim(); + if(str.Length == 0) continue; + + bool bFound = false; + foreach(string strEx in m_lProtocols) + { + if(strEx.Equals(str, StrUtil.CaseIgnoreCmp)) + { + bFound = true; + break; + } + } + + if(!bFound) m_lProtocols.Add(str); + } + } + } +} diff --git a/src/KeePassLib2Android/Serialization/IocPropertyInfoPool.cs b/src/KeePassLib2Android/Serialization/IocPropertyInfoPool.cs new file mode 100644 index 00000000..99b661f6 --- /dev/null +++ b/src/KeePassLib2Android/Serialization/IocPropertyInfoPool.cs @@ -0,0 +1,123 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +using KeePassLib.Resources; +using KeePassLib.Utility; + +namespace KeePassLib.Serialization +{ + public static class IocKnownProtocols + { + public const string Http = "HTTP"; + public const string Https = "HTTPS"; + public const string WebDav = "WebDAV"; + public const string Ftp = "FTP"; + } + + public static class IocKnownProperties + { + public const string Timeout = "Timeout"; + public const string PreAuth = "PreAuth"; + + public const string UserAgent = "UserAgent"; + public const string Expect100Continue = "Expect100Continue"; + + public const string Passive = "Passive"; + } + + public static class IocPropertyInfoPool + { + private static List m_l = null; + public static IEnumerable PropertyInfos + { + get { EnsureInitialized(); return m_l; } + } + + private static void EnsureInitialized() + { + if(m_l != null) return; + + string strGen = KLRes.General; + string strHttp = IocKnownProtocols.Http; + string strHttps = IocKnownProtocols.Https; + string strWebDav = IocKnownProtocols.WebDav; + string strFtp = IocKnownProtocols.Ftp; + + string[] vGen = new string[] { strGen }; + string[] vHttp = new string[] { strHttp, strHttps, strWebDav }; + string[] vFtp = new string[] { strFtp }; + + List l = new List(); + + l.Add(new IocPropertyInfo(IocKnownProperties.Timeout, + typeof(long), KLRes.Timeout + " [ms]", vGen)); + l.Add(new IocPropertyInfo(IocKnownProperties.PreAuth, + typeof(bool), KLRes.PreAuth, vGen)); + + l.Add(new IocPropertyInfo(IocKnownProperties.UserAgent, + typeof(string), KLRes.UserAgent, vHttp)); + l.Add(new IocPropertyInfo(IocKnownProperties.Expect100Continue, + typeof(bool), KLRes.Expect100Continue, vHttp)); + + l.Add(new IocPropertyInfo(IocKnownProperties.Passive, + typeof(bool), KLRes.Passive, vFtp)); + + // l.Add(new IocPropertyInfo("Test", typeof(bool), + // "Long long long long long long long long long long long long long long long long long long long long", + // new string[] { "Proto 1/9", "Proto 2/9", "Proto 3/9", "Proto 4/9", "Proto 5/9", + // "Proto 6/9", "Proto 7/9", "Proto 8/9", "Proto 9/9" })); + + m_l = l; + } + + public static IocPropertyInfo Get(string strName) + { + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return null; } + + EnsureInitialized(); + foreach(IocPropertyInfo pi in m_l) + { + if(pi.Name.Equals(strName, StrUtil.CaseIgnoreCmp)) + return pi; + } + + return null; + } + + public static bool Add(IocPropertyInfo pi) + { + if(pi == null) { Debug.Assert(false); return false; } + + // Name must be non-empty + string strName = pi.Name; + if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return false; } + + IocPropertyInfo piEx = Get(strName); // Ensures initialized + if(piEx != null) { Debug.Assert(false); return false; } // Exists already + + m_l.Add(pi); + return true; + } + } +} diff --git a/src/KeePassLib2Android/Serialization/KdbxFile.Read.Streamed.cs b/src/KeePassLib2Android/Serialization/KdbxFile.Read.Streamed.cs index 77ea8159..e0e0effb 100644 --- a/src/KeePassLib2Android/Serialization/KdbxFile.Read.Streamed.cs +++ b/src/KeePassLib2Android/Serialization/KdbxFile.Read.Streamed.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,18 +19,17 @@ using System; using System.Collections.Generic; -using System.Text; -using System.Security; -using System.Security.Cryptography; -using System.Drawing; -using System.Xml; -using System.IO; using System.Diagnostics; +using System.IO; +using System.Text; +using System.Xml; + +#if !KeePassUAP +using System.Drawing; +#endif using KeePassLib; using KeePassLib.Collections; -using KeePassLib.Cryptography; -using KeePassLib.Cryptography.Cipher; using KeePassLib.Interfaces; using KeePassLib.Resources; using KeePassLib.Security; @@ -45,49 +42,6 @@ namespace KeePassLib.Serialization /// public sealed partial class KdbxFile { - private class ColorTranslator - { - public static Color FromHtml(String colorString) - { - Color color; - - if (colorString.StartsWith("#")) - { - colorString = colorString.Substring(1); - } - if (colorString.EndsWith(";")) - { - colorString = colorString.Substring(0, colorString.Length - 1); - } - - int red, green, blue; - switch (colorString.Length) - { - case 6: - red = int.Parse(colorString.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); - green = int.Parse(colorString.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); - blue = int.Parse(colorString.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); - color = Color.FromArgb(red, green, blue); - break; - case 3: - red = int.Parse(colorString.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); - green = int.Parse(colorString.Substring(1, 1), System.Globalization.NumberStyles.HexNumber); - blue = int.Parse(colorString.Substring(2, 1), System.Globalization.NumberStyles.HexNumber); - color = Color.FromArgb(red, green, blue); - break; - case 1: - red = green = blue = int.Parse(colorString.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); - color = Color.FromArgb(red, green, blue); - break; - default: - throw new ArgumentException("Invalid color: " + colorString); - } - return color; - } - - } - - private enum KdbContext { Null, @@ -104,13 +58,17 @@ namespace KeePassLib.Serialization DeletedObject, Group, GroupTimes, + GroupCustomData, + GroupCustomDataItem, Entry, EntryTimes, EntryString, EntryBinary, EntryAutoType, EntryAutoTypeItem, - EntryHistory + EntryHistory, + EntryCustomData, + EntryCustomDataItem } private bool m_bReadNextNode = true; @@ -130,10 +88,14 @@ namespace KeePassLib.Serialization private byte[] m_pbCustomIconData = null; private string m_strCustomDataKey = null; private string m_strCustomDataValue = null; + private string m_strGroupCustomDataKey = null; + private string m_strGroupCustomDataValue = null; + private string m_strEntryCustomDataKey = null; + private string m_strEntryCustomDataValue = null; - private void ReadXmlStreamed(Stream readerStream, Stream sParentStream) + private void ReadXmlStreamed(Stream sXml, Stream sParent) { - ReadDocumentStreamed(CreateXmlReader(readerStream), sParentStream); + ReadDocumentStreamed(CreateXmlReader(sXml), sParent); } internal static XmlReaderSettings CreateStdXmlReaderSettings() @@ -145,9 +107,12 @@ namespace KeePassLib.Serialization xrs.IgnoreProcessingInstructions = true; xrs.IgnoreWhitespace = true; -#if !KeePassRT +#if KeePassUAP + xrs.DtdProcessing = DtdProcessing.Prohibit; +#else #if !KeePassLibSD - xrs.ProhibitDtd = true; + xrs.ProhibitDtd = true; // Obsolete in .NET 4, but still there + // xrs.DtdProcessing = DtdProcessing.Prohibit; // .NET 4 only #endif xrs.ValidationType = ValidationType.None; #endif @@ -258,15 +223,25 @@ namespace KeePassLib.Serialization ReadString(xr); // Ignore else if(xr.Name == ElemHeaderHash) { + // The header hash is typically only stored in + // KDBX <= 3.1 files, not in KDBX >= 4 files + // (here, the header is verified via a HMAC), + // but we also support it for KDBX >= 4 files + // (i.e. if it's present, we check it) + string strHash = ReadString(xr); if(!string.IsNullOrEmpty(strHash) && (m_pbHashOfHeader != null) && !m_bRepairMode) { + Debug.Assert(m_uFileVersion <= FileVersion32_3); + byte[] pbHash = Convert.FromBase64String(strHash); if(!MemUtil.ArraysEqual(pbHash, m_pbHashOfHeader)) throw new IOException(KLRes.FileCorrupted); } } + else if(xr.Name == ElemSettingsChanged) + m_pwDatabase.SettingsChanged = ReadTime(xr); else if(xr.Name == ElemDbName) m_pwDatabase.Name = ReadString(xr); else if(xr.Name == ElemDbNameChanged) @@ -426,6 +401,8 @@ namespace KeePassLib.Serialization m_ctxGroup.EnableSearching = StrUtil.StringToBoolEx(ReadString(xr)); else if(xr.Name == ElemLastTopVisibleEntry) m_ctxGroup.LastTopVisibleEntry = ReadUuid(xr); + else if(xr.Name == ElemCustomData) + return SwitchContext(ctx, KdbContext.GroupCustomData, xr); else if(xr.Name == ElemGroup) { m_ctxGroup = new PwGroup(false, false); @@ -446,6 +423,20 @@ namespace KeePassLib.Serialization else ReadUnknown(xr); break; + case KdbContext.GroupCustomData: + if(xr.Name == ElemStringDictExItem) + return SwitchContext(ctx, KdbContext.GroupCustomDataItem, xr); + else ReadUnknown(xr); + break; + + case KdbContext.GroupCustomDataItem: + if(xr.Name == ElemKey) + m_strGroupCustomDataKey = ReadString(xr); + else if(xr.Name == ElemValue) + m_strGroupCustomDataValue = ReadString(xr); + else ReadUnknown(xr); + break; + case KdbContext.Entry: if(xr.Name == ElemUuid) m_ctxEntry.Uuid = ReadUuid(xr); @@ -477,6 +468,8 @@ namespace KeePassLib.Serialization return SwitchContext(ctx, KdbContext.EntryBinary, xr); else if(xr.Name == ElemAutoType) return SwitchContext(ctx, KdbContext.EntryAutoType, xr); + else if(xr.Name == ElemCustomData) + return SwitchContext(ctx, KdbContext.EntryCustomData, xr); else if(xr.Name == ElemHistory) { Debug.Assert(m_bEntryInHistory == false); @@ -497,15 +490,15 @@ namespace KeePassLib.Serialization (ITimeLogger)m_ctxGroup : (ITimeLogger)m_ctxEntry); Debug.Assert(tl != null); - if(xr.Name == ElemLastModTime) - tl.SetLazyLastModificationTime(ReadString(xr)); - else if(xr.Name == ElemCreationTime) + if(xr.Name == ElemCreationTime) tl.SetLazyCreationTime(ReadString(xr)); - else if(xr.Name == ElemLastAccessTime) + else if (xr.Name == ElemLastModTime) + tl.SetLazyLastModificationTime(ReadString(xr)); + else if (xr.Name == ElemLastAccessTime) tl.SetLazyLastAccessTime(ReadString(xr)); - else if(xr.Name == ElemExpiryTime) + else if (xr.Name == ElemExpiryTime) tl.SetLazyExpiryTime(ReadString(xr)); - else if(xr.Name == ElemExpires) + else if (xr.Name == ElemExpires) tl.Expires = ReadBool(xr, false); else if(xr.Name == ElemUsageCount) tl.UsageCount = ReadULong(xr, 0); @@ -551,6 +544,20 @@ namespace KeePassLib.Serialization else ReadUnknown(xr); break; + case KdbContext.EntryCustomData: + if(xr.Name == ElemStringDictExItem) + return SwitchContext(ctx, KdbContext.EntryCustomDataItem, xr); + else ReadUnknown(xr); + break; + + case KdbContext.EntryCustomDataItem: + if(xr.Name == ElemKey) + m_strEntryCustomDataKey = ReadString(xr); + else if(xr.Name == ElemValue) + m_strEntryCustomDataValue = ReadString(xr); + else ReadUnknown(xr); + break; + case KdbContext.EntryHistory: if(xr.Name == ElemEntry) { @@ -652,6 +659,19 @@ namespace KeePassLib.Serialization } else if((ctx == KdbContext.GroupTimes) && (xr.Name == ElemTimes)) return KdbContext.Group; + else if((ctx == KdbContext.GroupCustomData) && (xr.Name == ElemCustomData)) + return KdbContext.Group; + else if((ctx == KdbContext.GroupCustomDataItem) && (xr.Name == ElemStringDictExItem)) + { + if((m_strGroupCustomDataKey != null) && (m_strGroupCustomDataValue != null)) + m_ctxGroup.CustomData.Set(m_strGroupCustomDataKey, m_strGroupCustomDataValue); + else { Debug.Assert(false); } + + m_strGroupCustomDataKey = null; + m_strGroupCustomDataValue = null; + + return KdbContext.GroupCustomData; + } else if((ctx == KdbContext.Entry) && (xr.Name == ElemEntry)) { // Create new UUID if absent @@ -702,6 +722,19 @@ namespace KeePassLib.Serialization m_ctxATSeq = null; return KdbContext.EntryAutoType; } + else if((ctx == KdbContext.EntryCustomData) && (xr.Name == ElemCustomData)) + return KdbContext.Entry; + else if((ctx == KdbContext.EntryCustomDataItem) && (xr.Name == ElemStringDictExItem)) + { + if((m_strEntryCustomDataKey != null) && (m_strEntryCustomDataValue != null)) + m_ctxEntry.CustomData.Set(m_strEntryCustomDataKey, m_strEntryCustomDataValue); + else { Debug.Assert(false); } + + m_strEntryCustomDataKey = null; + m_strEntryCustomDataValue = null; + + return KdbContext.EntryCustomData; + } else if((ctx == KdbContext.EntryHistory) && (xr.Name == ElemHistory)) { m_bEntryInHistory = false; @@ -852,7 +885,19 @@ namespace KeePassLib.Serialization if(strRef != null) { ProtectedBinary pb = BinPoolGet(strRef); - if(pb != null) return pb; + if(pb != null) + { + // https://sourceforge.net/p/keepass/feature-requests/2023/ + xr.MoveToElement(); +#if DEBUG + string strInner = ReadStringRaw(xr); + Debug.Assert(string.IsNullOrEmpty(strInner)); +#else + ReadStringRaw(xr); +#endif + + return pb; + } else { Debug.Assert(false); } } else { Debug.Assert(false); } @@ -914,7 +959,7 @@ namespace KeePassLib.Serialization byte[] pbEncrypted; if(strEncrypted.Length > 0) pbEncrypted = Convert.FromBase64String(strEncrypted); - else pbEncrypted = new byte[0]; + else pbEncrypted = MemUtil.EmptyByteArray; byte[] pbPad = m_randomStream.GetRandomBytes((uint)pbEncrypted.Length); diff --git a/src/KeePassLib2Android/Serialization/KdbxFile.Read.cs b/src/KeePassLib2Android/Serialization/KdbxFile.Read.cs index d5d82fab..1e4e17a5 100644 --- a/src/KeePassLib2Android/Serialization/KdbxFile.Read.cs +++ b/src/KeePassLib2Android/Serialization/KdbxFile.Read.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,25 +19,31 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; using System.Diagnostics; +using System.IO; using System.Security; -using System.Security.Cryptography; +using System.Text; using System.Xml; +#if !KeePassUAP +using System.Security.Cryptography; +#endif + #if !KeePassLibSD using System.IO.Compression; #else using KeePassLibSD; #endif +using KeePassLib.Collections; using KeePassLib.Cryptography; using KeePassLib.Cryptography.Cipher; +using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Interfaces; using KeePassLib.Keys; using KeePassLib.Resources; using KeePassLib.Utility; + using keepass2android; namespace KeePassLib.Serialization @@ -48,80 +54,119 @@ namespace KeePassLib.Serialization public sealed partial class KdbxFile { /// - /// Load a KDB file from a file. + /// Load a KDBX file. /// /// File to load. - /// Format specifier. + /// Format. /// Status logger (optional). - public void Load(string strFilePath, KdbxFormat kdbFormat, IStatusLogger slLogger) + public void Load(string strFilePath, KdbxFormat fmt, IStatusLogger slLogger) { IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath); - Load(IOConnection.OpenRead(ioc), kdbFormat, slLogger); + Load(IOConnection.OpenRead(ioc), fmt, slLogger); } /// - /// Load a KDB file from a stream. + /// Load a KDBX file from a stream. /// /// Stream to read the data from. Must contain /// a KDBX stream. - /// Format specifier. + /// Format. /// Status logger (optional). - public void Load(Stream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger) + public void Load(Stream sSource, KdbxFormat fmt, IStatusLogger slLogger) { Debug.Assert(sSource != null); if(sSource == null) throw new ArgumentNullException("sSource"); - m_format = kdbFormat; + m_format = fmt; m_slLogger = slLogger; - HashingStreamEx hashedStream = new HashingStreamEx(sSource, false, null); - UTF8Encoding encNoBom = StrUtil.Utf8; + byte[] pbCipherKey = null; + byte[] pbHmacKey64 = null; + + List lStreams = new List(); + lStreams.Add(sSource); + + HashingStreamEx sHashing = new HashingStreamEx(sSource, false, null); + lStreams.Add(sHashing); + try { - BinaryReaderEx br = null; - BinaryReaderEx brDecrypted = null; - Stream readerStream = null; - - if(kdbFormat == KdbxFormat.Default || kdbFormat == KdbxFormat.ProtocolBuffers) + Stream sXml; + if (fmt == KdbxFormat.Default || fmt == KdbxFormat.ProtocolBuffers) { - br = new BinaryReaderEx(hashedStream, encNoBom, KLRes.FileCorrupted); - ReadHeader(br); - - Stream sDecrypted = AttachStreamDecryptor(hashedStream); - if((sDecrypted == null) || (sDecrypted == hashedStream)) - throw new SecurityException(KLRes.CryptoStreamFailed); + BinaryReaderEx br = new BinaryReaderEx(sHashing, + encNoBom, KLRes.FileCorrupted); + byte[] pbHeader = LoadHeader(br); + int cbEncKey, cbEncIV; + ICipherEngine iCipher = GetCipher(out cbEncKey, out cbEncIV); + if (m_slLogger != null) m_slLogger.SetText("KP2AKEY_TransformingKey", LogStatusType.AdditionalInfo); + + ComputeKeys(out pbCipherKey, cbEncKey, out pbHmacKey64); - brDecrypted = new BinaryReaderEx(sDecrypted, encNoBom, KLRes.FileCorrupted); - byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32); - - if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32)) - throw new InvalidDataException(); - - if (m_slLogger != null) - m_slLogger.SetText("KP2AKEY_DecodingDatabase", LogStatusType.AdditionalInfo); - - for(int iStart = 0; iStart < 32; ++iStart) + Stream sPlain; + if(m_uFileVersion <= FileVersion32_3) { - if(pbStoredStartBytes[iStart] != m_pbStreamStartBytes[iStart]) - throw new InvalidCompositeKeyException(); - } + Stream sDecrypted = EncryptStream(sHashing, iCipher, + pbCipherKey, cbEncIV, false); + if((sDecrypted == null) || (sDecrypted == sHashing)) + throw new SecurityException(KLRes.CryptoStreamFailed); - Stream sHashed = new HashedBlockStream(sDecrypted, false, 0, - !m_bRepairMode); + if (m_slLogger != null) + m_slLogger.SetText("KP2AKEY_DecodingDatabase", LogStatusType.AdditionalInfo); + + lStreams.Add(sDecrypted); + + BinaryReaderEx brDecrypted = new BinaryReaderEx(sDecrypted, + encNoBom, KLRes.FileCorrupted); + byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32); + + if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32)) + throw new InvalidDataException(); + if(!MemUtil.ArraysEqual(pbStoredStartBytes, m_pbStreamStartBytes)) + throw new InvalidCompositeKeyException(); + + if (m_slLogger != null) + m_slLogger.SetText("KP2AKEY_DecodingDatabase", LogStatusType.AdditionalInfo); + + + sPlain = new HashedBlockStream(sDecrypted, false, 0, !m_bRepairMode); + } + else // KDBX >= 4 + { + byte[] pbHeaderHmac = ComputeHeaderHmac(pbHeader, pbHmacKey64); + byte[] pbStoredHmac = MemUtil.Read(sHashing, 32); + if((pbStoredHmac == null) || (pbStoredHmac.Length != 32)) + throw new InvalidDataException(); + if(!MemUtil.ArraysEqual(pbHeaderHmac, pbStoredHmac)) + throw new InvalidCompositeKeyException(); + + HmacBlockStream sBlocks = new HmacBlockStream(sHashing, + false, !m_bRepairMode, pbHmacKey64); + lStreams.Add(sBlocks); + + sPlain = EncryptStream(sBlocks, iCipher, pbCipherKey, + cbEncIV, false); + if((sPlain == null) || (sPlain == sBlocks)) + throw new SecurityException(KLRes.CryptoStreamFailed); + } + lStreams.Add(sPlain); if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip) - readerStream = new GZipStream(sHashed, CompressionMode.Decompress); - else readerStream = sHashed; + { + sXml = new GZipStream(sPlain, CompressionMode.Decompress); + lStreams.Add(sXml); + } + else sXml = sPlain; } - else if(kdbFormat == KdbxFormat.PlainXml) - readerStream = hashedStream; - else { Debug.Assert(false); throw new FormatException("KdbFormat"); } + else if(fmt == KdbxFormat.PlainXml) + sXml = sHashing; + else { Debug.Assert(false); throw new ArgumentOutOfRangeException("fmt"); } - if(kdbFormat != KdbxFormat.PlainXml) // Is an encrypted format + if(fmt == KdbxFormat.Default) { if(m_pbProtectedStreamKey == null) { @@ -135,39 +180,60 @@ namespace KeePassLib.Serialization else m_randomStream = null; // No random stream for plain-text files if (m_slLogger != null) m_slLogger.SetText("KP2AKEY_ParsingDatabase", LogStatusType.AdditionalInfo); + +#if KeePassDebug_WriteXml + // FileStream fsOut = new FileStream("Raw.xml", FileMode.Create, + // FileAccess.Write, FileShare.None); + // try + // { + // while(true) + // { + // int b = sXml.ReadByte(); + // if(b == -1) break; + // fsOut.WriteByte((byte)b); + // } + // } + // catch(Exception) { } + // fsOut.Close(); +#endif var stopWatch = Stopwatch.StartNew(); - if (kdbFormat == KdbxFormat.ProtocolBuffers) + if (fmt == KdbxFormat.ProtocolBuffers) { - KdbpFile.ReadDocument(m_pwDatabase, readerStream, m_pbProtectedStreamKey, m_pbHashOfHeader); + KdbpFile.ReadDocument(m_pwDatabase, sXml, m_pbProtectedStreamKey, m_pbHashOfHeader); Kp2aLog.Log(String.Format("KdbpFile.ReadDocument: {0}ms", stopWatch.ElapsedMilliseconds)); } else { - ReadXmlStreamed(readerStream, hashedStream); + + ReadXmlStreamed(sXml, sHashing); Kp2aLog.Log(String.Format("ReadXmlStreamed: {0}ms", stopWatch.ElapsedMilliseconds)); } - - readerStream.Close(); - // GC.KeepAlive(br); - // GC.KeepAlive(brDecrypted); + // ReadXmlDom(sXml); } catch(CryptographicException) // Thrown on invalid padding { throw new CryptographicException(KLRes.FileCorrupted); } - finally { CommonCleanUpRead(sSource, hashedStream); } + finally + { + if(pbCipherKey != null) MemUtil.ZeroByteArray(pbCipherKey); + if(pbHmacKey64 != null) MemUtil.ZeroByteArray(pbHmacKey64); + + CommonCleanUpRead(lStreams, sHashing); + } } - private void CommonCleanUpRead(Stream sSource, HashingStreamEx hashedStream) + private void CommonCleanUpRead(List lStreams, HashingStreamEx sHashing) { - hashedStream.Close(); - m_pbHashOfFileOnDisk = hashedStream.Hash; + CloseStreams(lStreams); - sSource.Close(); + Debug.Assert(lStreams.Contains(sHashing)); // sHashing must be closed + m_pbHashOfFileOnDisk = sHashing.Hash; + Debug.Assert(m_pbHashOfFileOnDisk != null); // Reset memory protection settings (to always use reasonable // defaults) @@ -180,10 +246,16 @@ namespace KeePassLib.Serialization // the history maintenance settings) m_pwDatabase.MaintainBackups(); // Don't mark database as modified + // Expand the root group, such that in case the user accidently + // collapses the root group he can simply reopen the database + PwGroup pgRoot = m_pwDatabase.RootGroup; + if(pgRoot != null) pgRoot.IsExpanded = true; + else { Debug.Assert(false); } + m_pbHashOfHeader = null; } - private void ReadHeader(BinaryReaderEx br) + private byte[] LoadHeader(BinaryReaderEx br) { MemoryStream msHeader = new MemoryStream(); Debug.Assert(br.CopyDataTo == null); @@ -208,18 +280,19 @@ namespace KeePassLib.Serialization if((uVersion & FileVersionCriticalMask) > (FileVersion32 & FileVersionCriticalMask)) throw new FormatException(KLRes.FileVersionUnsupported + MessageService.NewParagraph + KLRes.FileNewVerReq); + m_uFileVersion = uVersion; while(true) { - if(ReadHeaderField(br) == false) - break; + if(!ReadHeaderField(br)) break; } br.CopyDataTo = null; byte[] pbHeader = msHeader.ToArray(); msHeader.Close(); - SHA256Managed sha256 = new SHA256Managed(); - m_pbHashOfHeader = sha256.ComputeHash(pbHeader); + + m_pbHashOfHeader = CryptoUtil.HashSha256(pbHeader); + return pbHeader; } private bool ReadHeaderField(BinaryReaderEx brSource) @@ -228,15 +301,21 @@ namespace KeePassLib.Serialization if(brSource == null) throw new ArgumentNullException("brSource"); byte btFieldID = brSource.ReadByte(); - ushort uSize = MemUtil.BytesToUInt16(brSource.ReadBytes(2)); - byte[] pbData = null; - if(uSize > 0) + int cbSize; + Debug.Assert(m_uFileVersion > 0); + if(m_uFileVersion <= FileVersion32_3) + cbSize = (int)MemUtil.BytesToUInt16(brSource.ReadBytes(2)); + else cbSize = MemUtil.BytesToInt32(brSource.ReadBytes(4)); + if(cbSize < 0) throw new FormatException(KLRes.FileCorrupted); + + byte[] pbData = MemUtil.EmptyByteArray; + if(cbSize > 0) { string strPrevExcpText = brSource.ReadExceptionText; brSource.ReadExceptionText = KLRes.FileHeaderEndEarly; - pbData = brSource.ReadBytes(uSize); + pbData = brSource.ReadBytes(cbSize); brSource.ReadExceptionText = strPrevExcpText; } @@ -262,13 +341,27 @@ namespace KeePassLib.Serialization CryptoRandom.Instance.AddEntropy(pbData); break; + // Obsolete; for backward compatibility only case KdbxHeaderFieldID.TransformSeed: - m_pbTransformSeed = pbData; + AesKdf kdfS = new AesKdf(); + if(!m_pwDatabase.KdfParameters.KdfUuid.Equals(kdfS.Uuid)) + m_pwDatabase.KdfParameters = kdfS.GetDefaultParameters(); + + // m_pbTransformSeed = pbData; + m_pwDatabase.KdfParameters.SetByteArray(AesKdf.ParamSeed, pbData); + CryptoRandom.Instance.AddEntropy(pbData); break; + // Obsolete; for backward compatibility only case KdbxHeaderFieldID.TransformRounds: - m_pwDatabase.KeyEncryptionRounds = MemUtil.BytesToUInt64(pbData); + AesKdf kdfR = new AesKdf(); + if(!m_pwDatabase.KdfParameters.KdfUuid.Equals(kdfR.Uuid)) + m_pwDatabase.KdfParameters = kdfR.GetDefaultParameters(); + + // m_pwDatabase.KeyEncryptionRounds = MemUtil.BytesToUInt64(pbData); + m_pwDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds, + MemUtil.BytesToUInt64(pbData)); break; case KdbxHeaderFieldID.EncryptionIV: @@ -281,6 +374,7 @@ namespace KeePassLib.Serialization break; case KdbxHeaderFieldID.StreamStartBytes: + Debug.Assert(m_uFileVersion <= FileVersion32_3); m_pbStreamStartBytes = pbData; break; @@ -288,6 +382,15 @@ namespace KeePassLib.Serialization SetInnerRandomStreamID(pbData); break; + case KdbxHeaderFieldID.KdfParameters: + m_pwDatabase.KdfParameters = KdfParameters.DeserializeExt(pbData); + break; + + case KdbxHeaderFieldID.PublicCustomData: + Debug.Assert(m_pwDatabase.PublicCustomData.Count == 0); + m_pwDatabase.PublicCustomData = VariantDictionary.Deserialize(pbData); + break; + default: Debug.Assert(false); if(m_slLogger != null) @@ -301,7 +404,7 @@ namespace KeePassLib.Serialization private void SetCipher(byte[] pbID) { - if((pbID == null) || (pbID.Length != 16)) + if((pbID == null) || (pbID.Length != (int)PwUuid.UuidSize)) throw new FormatException(KLRes.FileUnknownCipher); m_pwDatabase.DataCipherUuid = new PwUuid(pbID); @@ -325,36 +428,6 @@ namespace KeePassLib.Serialization m_craInnerRandomStream = (CrsAlgorithm)uID; } - private Stream AttachStreamDecryptor(Stream s) - { - MemoryStream ms = new MemoryStream(); - - Debug.Assert(m_pbMasterSeed.Length == 32); - if(m_pbMasterSeed.Length != 32) - throw new FormatException(KLRes.MasterSeedLengthInvalid); - ms.Write(m_pbMasterSeed, 0, 32); - if (m_slLogger != null) - m_slLogger.SetText("KP2AKEY_TransformingKey", LogStatusType.AdditionalInfo); - byte[] pKey32 = m_pwDatabase.MasterKey.GenerateKey32(m_pbTransformSeed, - m_pwDatabase.KeyEncryptionRounds).ReadData(); - if((pKey32 == null) || (pKey32.Length != 32)) - throw new SecurityException(KLRes.InvalidCompositeKey); - ms.Write(pKey32, 0, 32); - - SHA256Managed sha256 = new SHA256Managed(); - byte[] aesKey = sha256.ComputeHash(ms.ToArray()); - - ms.Close(); - Array.Clear(pKey32, 0, 32); - - if((aesKey == null) || (aesKey.Length != 32)) - throw new SecurityException(KLRes.FinalKeyCreationFailed); - - ICipherEngine iEngine = CipherPool.GlobalPool.GetCipher(m_pwDatabase.DataCipherUuid); - if(iEngine == null) throw new SecurityException(KLRes.FileUnknownCipher); - return iEngine.DecryptStream(s, aesKey, m_pbEncryptionIV); - } - [Obsolete] public static List ReadEntries(PwDatabase pwDatabase, Stream msData) { diff --git a/src/KeePassLib2Android/Serialization/KdbxFile.Write.cs b/src/KeePassLib2Android/Serialization/KdbxFile.Write.cs index a61e9bef..a000a188 100644 --- a/src/KeePassLib2Android/Serialization/KdbxFile.Write.cs +++ b/src/KeePassLib2Android/Serialization/KdbxFile.Write.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,30 +19,35 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Xml; -using System.Security; -using System.Security.Cryptography; -using System.Drawing; -using System.Globalization; using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Security; +using System.Text; +using System.Xml; -#if !KeePassLibSD -using System.IO.Compression; -#else +#if !KeePassUAP +using System.Drawing; +using System.Security.Cryptography; +#endif + +#if KeePassLibSD using KeePassLibSD; +#else +using System.IO.Compression; #endif using KeePassLib.Collections; using KeePassLib.Cryptography; using KeePassLib.Cryptography.Cipher; +using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Delegates; using KeePassLib.Interfaces; using KeePassLib.Keys; using KeePassLib.Resources; using KeePassLib.Security; using KeePassLib.Utility; + using keepass2android; namespace KeePassLib.Serialization @@ -54,7 +57,7 @@ namespace KeePassLib.Serialization /// public sealed partial class KdbxFile { - // public void Save(string strFile, PwGroup pgDataSource, KdbxFormat format, + // public void Save(string strFile, PwGroup pgDataSource, KdbxFormat fmt, // IStatusLogger slLogger) // { // bool bMadeUnhidden = UrlUtil.UnhideFile(strFile); @@ -72,175 +75,257 @@ namespace KeePassLib.Serialization /// Group containing all groups and /// entries to write. If null, the complete database will /// be written. - /// Format of the file to create. + /// Format of the file to create. /// Logger that recieves status information. - public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat format, + public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat fmt, IStatusLogger slLogger) { Debug.Assert(sSaveTo != null); if(sSaveTo == null) throw new ArgumentNullException("sSaveTo"); - m_format = format; + m_format = fmt; m_slLogger = slLogger; - HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo, true, null); - UTF8Encoding encNoBom = StrUtil.Utf8; CryptoRandom cr = CryptoRandom.Instance; + byte[] pbCipherKey = null; + byte[] pbHmacKey64 = null; + + List lStreams = new List(); + lStreams.Add(sSaveTo); + + HashingStreamEx sHashing = new HashingStreamEx(sSaveTo, true, null); + lStreams.Add(sHashing); try { - m_pbMasterSeed = cr.GetRandomBytes(32); - m_pbTransformSeed = cr.GetRandomBytes(32); - m_pbEncryptionIV = cr.GetRandomBytes(16); + m_uFileVersion = GetMinKdbxVersion(); - m_pbProtectedStreamKey = cr.GetRandomBytes(32); - m_craInnerRandomStream = CrsAlgorithm.Salsa20; + int cbEncKey, cbEncIV; + ICipherEngine iCipher = GetCipher(out cbEncKey, out cbEncIV); + + m_pbMasterSeed = cr.GetRandomBytes(32); + m_pbEncryptionIV = cr.GetRandomBytes((uint)cbEncIV); + + // m_pbTransformSeed = cr.GetRandomBytes(32); + PwUuid puKdf = m_pwDatabase.KdfParameters.KdfUuid; + KdfEngine kdf = KdfPool.Get(puKdf); + if(kdf == null) + throw new Exception(KLRes.UnknownKdf + MessageService.NewParagraph + + // KLRes.FileNewVerOrPlgReq + MessageService.NewParagraph + + "UUID: " + puKdf.ToHexString() + "."); + kdf.Randomize(m_pwDatabase.KdfParameters); + + if(m_uFileVersion <= FileVersion32_3) + { + m_craInnerRandomStream = CrsAlgorithm.Salsa20; + m_pbProtectedStreamKey = cr.GetRandomBytes(32); + } + else // KDBX >= 4 + { + m_craInnerRandomStream = CrsAlgorithm.ChaCha20; + m_pbProtectedStreamKey = cr.GetRandomBytes(64); + } m_randomStream = new CryptoRandomStream(m_craInnerRandomStream, m_pbProtectedStreamKey); - m_pbStreamStartBytes = cr.GetRandomBytes(32); + if(m_uFileVersion <= FileVersion32_3) + m_pbStreamStartBytes = cr.GetRandomBytes(32); - Stream writerStream; - if(m_format == KdbxFormat.Default || m_format == KdbxFormat.ProtocolBuffers) + Stream sXml; + if (m_format == KdbxFormat.Default || m_format == KdbxFormat.ProtocolBuffers) { - WriteHeader(hashedStream); // Also flushes the stream + byte[] pbHeader = GenerateHeader(); + m_pbHashOfHeader = CryptoUtil.HashSha256(pbHeader); - Stream sEncrypted = AttachStreamEncryptor(hashedStream); - if((sEncrypted == null) || (sEncrypted == hashedStream)) - throw new SecurityException(KLRes.CryptoStreamFailed); + MemUtil.Write(sHashing, pbHeader); + sHashing.Flush(); - sEncrypted.Write(m_pbStreamStartBytes, 0, m_pbStreamStartBytes.Length); + ComputeKeys(out pbCipherKey, cbEncKey, out pbHmacKey64); - Stream sHashed = new HashedBlockStream(sEncrypted, true); + Stream sPlain; + if(m_uFileVersion <= FileVersion32_3) + { + Stream sEncrypted = EncryptStream(sHashing, iCipher, + pbCipherKey, cbEncIV, true); + if((sEncrypted == null) || (sEncrypted == sHashing)) + throw new SecurityException(KLRes.CryptoStreamFailed); + lStreams.Add(sEncrypted); + + MemUtil.Write(sEncrypted, m_pbStreamStartBytes); + + sPlain = new HashedBlockStream(sEncrypted, true); + } + else // KDBX >= 4 + { + byte[] pbHeaderHmac = ComputeHeaderHmac(pbHeader, pbHmacKey64); + MemUtil.Write(sHashing, pbHeaderHmac); + + Stream sBlocks = new HmacBlockStream(sHashing, true, + true, pbHmacKey64); + lStreams.Add(sBlocks); + + sPlain = EncryptStream(sBlocks, iCipher, pbCipherKey, + cbEncIV, true); + if((sPlain == null) || (sPlain == sBlocks)) + throw new SecurityException(KLRes.CryptoStreamFailed); + } + lStreams.Add(sPlain); if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip) - writerStream = new GZipStream(sHashed, CompressionMode.Compress); - else - writerStream = sHashed; + { + sXml = new GZipStream(sPlain, CompressionMode.Compress); + lStreams.Add(sXml); + } + else sXml = sPlain; } else if(m_format == KdbxFormat.PlainXml) - writerStream = hashedStream; - else { Debug.Assert(false); throw new FormatException("KdbFormat"); } + sXml = sHashing; + else + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("fmt"); + } var stopWatch = Stopwatch.StartNew(); if (m_format == KdbxFormat.ProtocolBuffers) { - KdbpFile.WriteDocument(m_pwDatabase, writerStream, m_pbProtectedStreamKey, m_pbHashOfHeader); + KdbpFile.WriteDocument(m_pwDatabase, sXml, m_pbProtectedStreamKey, m_pbHashOfHeader); } else { - m_xmlWriter = new XmlTextWriter(writerStream, encNoBom); + +#if KeePassUAP + XmlWriterSettings xws = new XmlWriterSettings(); + xws.Encoding = encNoBom; + xws.Indent = true; + xws.IndentChars = "\t"; + xws.NewLineOnAttributes = false; + + XmlWriter xw = XmlWriter.Create(sXml, xws); +#else + XmlTextWriter xw = new XmlTextWriter(sXml, encNoBom); + + xw.Formatting = Formatting.Indented; + xw.IndentChar = '\t'; + xw.Indentation = 1; +#endif + m_xmlWriter = xw; + WriteDocument(pgDataSource); m_xmlWriter.Flush(); m_xmlWriter.Close(); } - - writerStream.Close(); - Kp2aLog.Log(String.Format("{1}: {0}ms", stopWatch.ElapsedMilliseconds, m_format == KdbxFormat.ProtocolBuffers ? "KdbpFile.WriteDocument" : "Xml WriteDocument")); + } - finally { CommonCleanUpWrite(sSaveTo, hashedStream); } + finally + { + if(pbCipherKey != null) MemUtil.ZeroByteArray(pbCipherKey); + if(pbHmacKey64 != null) MemUtil.ZeroByteArray(pbHmacKey64); + + CommonCleanUpWrite(lStreams, sHashing); + } + } - private void CommonCleanUpWrite(Stream sSaveTo, HashingStreamEx hashedStream) + private void CommonCleanUpWrite(List lStreams, HashingStreamEx sHashing) { - hashedStream.Close(); - m_pbHashOfFileOnDisk = hashedStream.Hash; + CloseStreams(lStreams); - sSaveTo.Close(); + Debug.Assert(lStreams.Contains(sHashing)); // sHashing must be closed + m_pbHashOfFileOnDisk = sHashing.Hash; + Debug.Assert(m_pbHashOfFileOnDisk != null); m_xmlWriter = null; m_pbHashOfHeader = null; } - private void WriteHeader(Stream s) + private byte[] GenerateHeader() { - MemoryStream ms = new MemoryStream(); + byte[] pbHeader; + using(MemoryStream ms = new MemoryStream()) + { + MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature1)); + MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature2)); + MemUtil.Write(ms, MemUtil.UInt32ToBytes(m_uFileVersion)); - MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature1)); - MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature2)); - MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileVersion32)); + WriteHeaderField(ms, KdbxHeaderFieldID.CipherID, + m_pwDatabase.DataCipherUuid.UuidBytes); - WriteHeaderField(ms, KdbxHeaderFieldID.CipherID, - m_pwDatabase.DataCipherUuid.UuidBytes); + int nCprID = (int)m_pwDatabase.Compression; + WriteHeaderField(ms, KdbxHeaderFieldID.CompressionFlags, + MemUtil.UInt32ToBytes((uint)nCprID)); - int nCprID = (int)m_pwDatabase.Compression; - WriteHeaderField(ms, KdbxHeaderFieldID.CompressionFlags, - MemUtil.UInt32ToBytes((uint)nCprID)); + WriteHeaderField(ms, KdbxHeaderFieldID.MasterSeed, m_pbMasterSeed); - WriteHeaderField(ms, KdbxHeaderFieldID.MasterSeed, m_pbMasterSeed); - WriteHeaderField(ms, KdbxHeaderFieldID.TransformSeed, m_pbTransformSeed); - WriteHeaderField(ms, KdbxHeaderFieldID.TransformRounds, - MemUtil.UInt64ToBytes(m_pwDatabase.KeyEncryptionRounds)); - WriteHeaderField(ms, KdbxHeaderFieldID.EncryptionIV, m_pbEncryptionIV); - WriteHeaderField(ms, KdbxHeaderFieldID.ProtectedStreamKey, m_pbProtectedStreamKey); - WriteHeaderField(ms, KdbxHeaderFieldID.StreamStartBytes, m_pbStreamStartBytes); + if(m_uFileVersion <= FileVersion32_3) + { + Debug.Assert(m_pwDatabase.KdfParameters.KdfUuid.Equals( + (new AesKdf()).Uuid)); + WriteHeaderField(ms, KdbxHeaderFieldID.TransformSeed, + m_pwDatabase.KdfParameters.GetByteArray(AesKdf.ParamSeed)); + WriteHeaderField(ms, KdbxHeaderFieldID.TransformRounds, + MemUtil.UInt64ToBytes(m_pwDatabase.KdfParameters.GetUInt64( + AesKdf.ParamRounds, PwDefs.DefaultKeyEncryptionRounds))); + } + else + WriteHeaderField(ms, KdbxHeaderFieldID.KdfParameters, + KdfParameters.SerializeExt(m_pwDatabase.KdfParameters)); - int nIrsID = (int)m_craInnerRandomStream; - WriteHeaderField(ms, KdbxHeaderFieldID.InnerRandomStreamID, - MemUtil.UInt32ToBytes((uint)nIrsID)); + if(m_pbEncryptionIV.Length > 0) + WriteHeaderField(ms, KdbxHeaderFieldID.EncryptionIV, m_pbEncryptionIV); - WriteHeaderField(ms, KdbxHeaderFieldID.EndOfHeader, new byte[]{ - (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' }); + WriteHeaderField(ms, KdbxHeaderFieldID.ProtectedStreamKey, m_pbProtectedStreamKey); - byte[] pbHeader = ms.ToArray(); - ms.Close(); + if(m_uFileVersion <= FileVersion32_3) + WriteHeaderField(ms, KdbxHeaderFieldID.StreamStartBytes, + m_pbStreamStartBytes); - SHA256Managed sha256 = new SHA256Managed(); - m_pbHashOfHeader = sha256.ComputeHash(pbHeader); + int nIrsID = (int)m_craInnerRandomStream; + WriteHeaderField(ms, KdbxHeaderFieldID.InnerRandomStreamID, + MemUtil.Int32ToBytes(nIrsID)); - s.Write(pbHeader, 0, pbHeader.Length); - s.Flush(); + // Write public custom data only when there is at least one item, + // because KDBX 3.1 didn't support this field yet + if(m_pwDatabase.PublicCustomData.Count > 0) + WriteHeaderField(ms, KdbxHeaderFieldID.PublicCustomData, + VariantDictionary.Serialize(m_pwDatabase.PublicCustomData)); + + WriteHeaderField(ms, KdbxHeaderFieldID.EndOfHeader, new byte[] { + (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' }); + + pbHeader = ms.ToArray(); + } + + return pbHeader; } - private static void WriteHeaderField(Stream s, KdbxHeaderFieldID kdbID, + private void WriteHeaderField(Stream s, KdbxHeaderFieldID kdbID, byte[] pbData) { s.WriteByte((byte)kdbID); - if(pbData != null) + byte[] pb = (pbData ?? MemUtil.EmptyByteArray); + int cb = pb.Length; + if(cb < 0) { Debug.Assert(false); throw new OutOfMemoryException(); } + + Debug.Assert(m_uFileVersion > 0); + if(m_uFileVersion <= FileVersion32_3) { - ushort uLength = (ushort)pbData.Length; - MemUtil.Write(s, MemUtil.UInt16ToBytes(uLength)); + if(cb > (int)ushort.MaxValue) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("pbData"); + } - if(uLength > 0) s.Write(pbData, 0, pbData.Length); + MemUtil.Write(s, MemUtil.UInt16ToBytes((ushort)cb)); } - else MemUtil.Write(s, MemUtil.UInt16ToBytes((ushort)0)); - } + else MemUtil.Write(s, MemUtil.Int32ToBytes(cb)); - private Stream AttachStreamEncryptor(Stream s) - { - MemoryStream ms = new MemoryStream(); - - Debug.Assert(m_pbMasterSeed != null); - Debug.Assert(m_pbMasterSeed.Length == 32); - ms.Write(m_pbMasterSeed, 0, 32); - - Debug.Assert(m_pwDatabase != null); - Debug.Assert(m_pwDatabase.MasterKey != null); - ProtectedBinary pbinKey = m_pwDatabase.MasterKey.GenerateKey32( - m_pbTransformSeed, m_pwDatabase.KeyEncryptionRounds); - Debug.Assert(pbinKey != null); - if(pbinKey == null) - throw new SecurityException(KLRes.InvalidCompositeKey); - byte[] pKey32 = pbinKey.ReadData(); - if((pKey32 == null) || (pKey32.Length != 32)) - throw new SecurityException(KLRes.InvalidCompositeKey); - ms.Write(pKey32, 0, 32); - - SHA256Managed sha256 = new SHA256Managed(); - byte[] aesKey = sha256.ComputeHash(ms.ToArray()); - - ms.Close(); - Array.Clear(pKey32, 0, 32); - - Debug.Assert(CipherPool.GlobalPool != null); - ICipherEngine iEngine = CipherPool.GlobalPool.GetCipher(m_pwDatabase.DataCipherUuid); - if(iEngine == null) throw new SecurityException(KLRes.FileUnknownCipher); - return iEngine.EncryptStream(s, aesKey, m_pbEncryptionIV); + if(cb > 0) s.Write(pb, 0, cb); } private void WriteDocument(PwGroup pgDataSource) @@ -255,10 +340,6 @@ namespace KeePassLib.Serialization BinPoolBuild(pgRoot); - m_xmlWriter.Formatting = Formatting.Indented; - m_xmlWriter.IndentChar = '\t'; - m_xmlWriter.Indentation = 1; - m_xmlWriter.WriteStartDocument(true); m_xmlWriter.WriteStartElement(ElemDocNode); @@ -330,12 +411,15 @@ namespace KeePassLib.Serialization { m_xmlWriter.WriteStartElement(ElemMeta); - WriteObject(ElemGenerator, PwDatabase.LocalizedAppName, false); // Generator name + WriteObject(ElemGenerator, PwDatabase.LocalizedAppName, false); - if(m_pbHashOfHeader != null) + if((m_pbHashOfHeader != null) && (m_uFileVersion <= FileVersion32_3)) WriteObject(ElemHeaderHash, Convert.ToBase64String( m_pbHashOfHeader), false); + if(m_uFileVersion > FileVersion32_3) + WriteObject(ElemSettingsChanged, m_pwDatabase.SettingsChanged); + WriteObject(ElemDbName, m_pwDatabase.Name, true); WriteObject(ElemDbNameChanged, m_pwDatabase.NameChanged); WriteObject(ElemDbDesc, m_pwDatabase.Description, true); @@ -386,6 +470,9 @@ namespace KeePassLib.Serialization WriteObject(ElemEnableAutoType, StrUtil.BoolToStringEx(pg.EnableAutoType), false); WriteObject(ElemEnableSearching, StrUtil.BoolToStringEx(pg.EnableSearching), false); WriteObject(ElemLastTopVisibleEntry, pg.LastTopVisibleEntry); + + if(pg.CustomData.Count > 0) + WriteList(ElemCustomData, pg.CustomData); } private void EndGroup() @@ -401,7 +488,7 @@ namespace KeePassLib.Serialization WriteObject(ElemUuid, pe.Uuid); WriteObject(ElemIcon, (int)pe.IconId); - + if(!pe.CustomIconUuid.Equals(PwUuid.Zero)) WriteObject(ElemCustomIconID, pe.CustomIconUuid); @@ -416,6 +503,9 @@ namespace KeePassLib.Serialization WriteList(pe.Binaries); WriteList(ElemAutoType, pe.AutoType); + if(pe.CustomData.Count > 0) + WriteList(ElemCustomData, pe.CustomData); + if(!bIsHistory) WriteList(ElemHistory, pe.History, true); else { Debug.Assert(pe.History.UCount == 0); } @@ -468,8 +558,8 @@ namespace KeePassLib.Serialization m_xmlWriter.WriteStartElement(name); - WriteObject(ElemLastModTime, times.LastModificationTime); WriteObject(ElemCreationTime, times.CreationTime); + WriteObject(ElemLastModTime, times.LastModificationTime); WriteObject(ElemLastAccessTime, times.LastAccessTime); WriteObject(ElemExpiryTime, times.ExpiryTime); WriteObject(ElemExpires, times.Expires); diff --git a/src/KeePassLib2Android/Serialization/KdbxFile.cs b/src/KeePassLib2Android/Serialization/KdbxFile.cs index 84d056d2..2a5a872e 100644 --- a/src/KeePassLib2Android/Serialization/KdbxFile.cs +++ b/src/KeePassLib2Android/Serialization/KdbxFile.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,20 +19,25 @@ using System; using System.Collections.Generic; -using System.Xml; -using System.Text; +using System.Diagnostics; +using System.Drawing; using System.Globalization; using System.IO; -using System.Diagnostics; +using System.Security; +using System.Text; +using System.Xml; -#if !KeePassLibSD -using System.IO.Compression; +#if !KeePassUAP +using System.Security.Cryptography; #endif using KeePassLib.Collections; using KeePassLib.Cryptography; +using KeePassLib.Cryptography.Cipher; +using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Delegates; using KeePassLib.Interfaces; +using KeePassLib.Resources; using KeePassLib.Security; using KeePassLib.Utility; @@ -61,6 +66,47 @@ namespace KeePassLib.Serialization /// public sealed partial class KdbxFile { + private class ColorTranslator + { + public static Color FromHtml(String colorString) + { + Color color; + + if (colorString.StartsWith("#")) + { + colorString = colorString.Substring(1); + } + if (colorString.EndsWith(";")) + { + colorString = colorString.Substring(0, colorString.Length - 1); + } + + int red, green, blue; + switch (colorString.Length) + { + case 6: + red = int.Parse(colorString.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); + green = int.Parse(colorString.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); + blue = int.Parse(colorString.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); + color = Color.FromArgb(red, green, blue); + break; + case 3: + red = int.Parse(colorString.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); + green = int.Parse(colorString.Substring(1, 1), System.Globalization.NumberStyles.HexNumber); + blue = int.Parse(colorString.Substring(2, 1), System.Globalization.NumberStyles.HexNumber); + color = Color.FromArgb(red, green, blue); + break; + case 1: + red = green = blue = int.Parse(colorString.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); + color = Color.FromArgb(red, green, blue); + break; + default: + throw new ArgumentException("Invalid color: " + colorString); + } + return color; + } + + } /// /// File identifier, first 32-bit value. /// @@ -78,7 +124,8 @@ namespace KeePassLib.Serialization /// The first 2 bytes are critical (i.e. loading will fail, if the /// file version is too high), the last 2 bytes are informational. /// - private const uint FileVersion32 = 0x00030001; + private const uint FileVersion32 = 0x00040000; + private const uint FileVersion32_3 = 0x00030001; // Old format private const uint FileVersionCriticalMask = 0xFFFF0000; @@ -97,6 +144,7 @@ namespace KeePassLib.Serialization private const string ElemGenerator = "Generator"; private const string ElemHeaderHash = "HeaderHash"; + private const string ElemSettingsChanged = "SettingsChanged"; private const string ElemDbName = "DatabaseName"; private const string ElemDbNameChanged = "DatabaseNameChanged"; private const string ElemDbDesc = "DatabaseDescription"; @@ -192,19 +240,20 @@ namespace KeePassLib.Serialization private PwDatabase m_pwDatabase; // Not null, see constructor - private XmlTextWriter m_xmlWriter = null; + private XmlWriter m_xmlWriter = null; private CryptoRandomStream m_randomStream = null; private KdbxFormat m_format = KdbxFormat.Default; private IStatusLogger m_slLogger = null; + private uint m_uFileVersion = 0; private byte[] m_pbMasterSeed = null; - private byte[] m_pbTransformSeed = null; + // private byte[] m_pbTransformSeed = null; private byte[] m_pbEncryptionIV = null; private byte[] m_pbProtectedStreamKey = null; private byte[] m_pbStreamStartBytes = null; - // ArcFourVariant only for compatibility; KeePass will default to a - // different (more secure) algorithm when *writing* databases + // ArcFourVariant only for backward compatibility; KeePass defaults + // to a more secure algorithm when *writing* databases private CrsAlgorithm m_craInnerRandomStream = CrsAlgorithm.ArcFourVariant; private Dictionary m_dictBinPool = @@ -227,12 +276,14 @@ namespace KeePassLib.Serialization CipherID = 2, CompressionFlags = 3, MasterSeed = 4, - TransformSeed = 5, - TransformRounds = 6, + TransformSeed = 5, // KDBX 3.1, for backward compatibility only + TransformRounds = 6, // KDBX 3.1, for backward compatibility only EncryptionIV = 7, ProtectedStreamKey = 8, - StreamStartBytes = 9, - InnerRandomStreamID = 10 + StreamStartBytes = 9, // KDBX 3.1, for backward compatibility only + InnerRandomStreamID = 10, + KdfParameters = 11, // KDBX 4 + PublicCustomData = 12 // KDBX 4 } public byte[] HashOfFileOnDisk @@ -291,6 +342,152 @@ namespace KeePassLib.Serialization } } + private uint GetMinKdbxVersion() + { + AesKdf kdfAes = new AesKdf(); + if(!kdfAes.Uuid.Equals(m_pwDatabase.KdfParameters.KdfUuid)) + return FileVersion32; + + if(m_pwDatabase.PublicCustomData.Count > 0) + return FileVersion32; + + bool bCustomData = false; + GroupHandler gh = delegate(PwGroup pg) + { + if(pg == null) { Debug.Assert(false); return true; } + if(pg.CustomData.Count > 0) { bCustomData = true; return false; } + return true; + }; + EntryHandler eh = delegate(PwEntry pe) + { + if(pe == null) { Debug.Assert(false); return true; } + if(pe.CustomData.Count > 0) { bCustomData = true; return false; } + return true; + }; + gh(m_pwDatabase.RootGroup); + m_pwDatabase.RootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh); + if(bCustomData) return FileVersion32; + + return FileVersion32_3; // KDBX 3.1 is sufficient + } + + private void ComputeKeys(out byte[] pbCipherKey, int cbCipherKey, + out byte[] pbHmacKey64) + { + byte[] pbCmp = new byte[32 + 32 + 1]; + try + { + Debug.Assert(m_pbMasterSeed != null); + if(m_pbMasterSeed == null) + throw new ArgumentNullException("m_pbMasterSeed"); + Debug.Assert(m_pbMasterSeed.Length == 32); + if(m_pbMasterSeed.Length != 32) + throw new FormatException(KLRes.MasterSeedLengthInvalid); + Array.Copy(m_pbMasterSeed, 0, pbCmp, 0, 32); + + Debug.Assert(m_pwDatabase != null); + Debug.Assert(m_pwDatabase.MasterKey != null); + ProtectedBinary pbinUser = m_pwDatabase.MasterKey.GenerateKey32( + m_pwDatabase.KdfParameters); + Debug.Assert(pbinUser != null); + if(pbinUser == null) + throw new SecurityException(KLRes.InvalidCompositeKey); + byte[] pUserKey32 = pbinUser.ReadData(); + if((pUserKey32 == null) || (pUserKey32.Length != 32)) + throw new SecurityException(KLRes.InvalidCompositeKey); + Array.Copy(pUserKey32, 0, pbCmp, 32, 32); + MemUtil.ZeroByteArray(pUserKey32); + + pbCipherKey = CryptoUtil.ResizeKey(pbCmp, 0, 64, cbCipherKey); + + pbCmp[64] = 1; + using(SHA512Managed h = new SHA512Managed()) + { + pbHmacKey64 = h.ComputeHash(pbCmp); + } + } + finally { MemUtil.ZeroByteArray(pbCmp); } + } + + private ICipherEngine GetCipher(out int cbEncKey, out int cbEncIV) + { + PwUuid pu = m_pwDatabase.DataCipherUuid; + ICipherEngine iCipher = CipherPool.GlobalPool.GetCipher(pu); + if(iCipher == null) // CryptographicExceptions are translated to "file corrupted" + throw new Exception(KLRes.FileUnknownCipher + + MessageService.NewParagraph + KLRes.FileNewVerOrPlgReq + + MessageService.NewParagraph + "UUID: " + pu.ToHexString() + "."); + + ICipherEngine2 iCipher2 = (iCipher as ICipherEngine2); + if(iCipher2 != null) + { + cbEncKey = iCipher2.KeyLength; + if(cbEncKey < 0) throw new InvalidOperationException("EncKey.Length"); + + cbEncIV = iCipher2.IVLength; + if(cbEncIV < 0) throw new InvalidOperationException("EncIV.Length"); + } + else + { + cbEncKey = 32; + cbEncIV = 16; + } + + return iCipher; + } + + private Stream EncryptStream(Stream s, ICipherEngine iCipher, + byte[] pbKey, int cbIV, bool bEncrypt) + { + byte[] pbIV = (m_pbEncryptionIV ?? MemUtil.EmptyByteArray); + if(pbIV.Length != cbIV) + { + Debug.Assert(false); + throw new Exception(KLRes.FileCorrupted); + } + + if(bEncrypt) + return iCipher.EncryptStream(s, pbKey, pbIV); + return iCipher.DecryptStream(s, pbKey, pbIV); + } + + private byte[] ComputeHeaderHmac(byte[] pbHeader, byte[] pbKey) + { + byte[] pbHeaderHmac; + byte[] pbBlockKey = HmacBlockStream.GetHmacKey64( + pbKey, ulong.MaxValue); + using(HMACSHA256 h = new HMACSHA256(pbBlockKey)) + { + pbHeaderHmac = h.ComputeHash(pbHeader); + } + MemUtil.ZeroByteArray(pbBlockKey); + + return pbHeaderHmac; + } + + private void CloseStreams(List lStreams) + { + if(lStreams == null) { Debug.Assert(false); return; } + + // Typically, closing a stream also closes its base + // stream; however, there may be streams that do not + // do this (e.g. some cipher plugin), thus for safety + // we close all streams manually, from the innermost + // to the outermost + + for(int i = lStreams.Count - 1; i >= 0; --i) + { + // Check for duplicates + Debug.Assert((lStreams.IndexOf(lStreams[i]) == i) && + (lStreams.LastIndexOf(lStreams[i]) == i)); + + try { lStreams[i].Close(); } + catch(Exception) { Debug.Assert(false); } + } + + // Do not clear the list + } + private void BinPoolBuild(PwGroup pgDataSource) { m_dictBinPool = new Dictionary(); diff --git a/src/KeePassLib2Android/Serialization/OldFormatException.cs b/src/KeePassLib2Android/Serialization/OldFormatException.cs index b8ff3017..f05de4a4 100644 --- a/src/KeePassLib2Android/Serialization/OldFormatException.cs +++ b/src/KeePassLib2Android/Serialization/OldFormatException.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Translation/KPStringTable.cs b/src/KeePassLib2Android/Translation/KPStringTable.cs index 047110bf..cafb2b5a 100644 --- a/src/KeePassLib2Android/Translation/KPStringTable.cs +++ b/src/KeePassLib2Android/Translation/KPStringTable.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,15 +19,13 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Text; using System.Xml.Serialization; -using System.Diagnostics; namespace KeePassLib.Translation { - public class ToolStripItemCollection - {} public sealed class KPStringTable { private string m_strName = string.Empty; @@ -69,9 +65,9 @@ namespace KeePassLib.Translation return dict; } - -#if (!KeePassLibSD && !KeePassRT) - /*public void ApplyTo(ToolStripItemCollection tsic) + /* +#if (!KeePassLibSD && !KeePassUAP) + public void ApplyTo(ToolStripItemCollection tsic) { if(tsic == null) throw new ArgumentNullException("tsic"); @@ -97,7 +93,7 @@ namespace KeePassLib.Translation if((tsmi != null) && (tsmi.DropDownItems != null)) this.ApplyTo(tsmi.DropDownItems); } - }*/ -#endif + } +#endif*/ } } diff --git a/src/KeePassLib2Android/Translation/KPStringTableItem.cs b/src/KeePassLib2Android/Translation/KPStringTableItem.cs index 9fc27811..3106fa71 100644 --- a/src/KeePassLib2Android/Translation/KPStringTableItem.cs +++ b/src/KeePassLib2Android/Translation/KPStringTableItem.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Translation/KPTranslation.cs b/src/KeePassLib2Android/Translation/KPTranslation.cs index 32b01089..e7a68269 100644 --- a/src/KeePassLib2Android/Translation/KPTranslation.cs +++ b/src/KeePassLib2Android/Translation/KPTranslation.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,24 +19,22 @@ using System; using System.Collections.Generic; -using System.Text; +using System.ComponentModel; +using System.Diagnostics; using System.IO; +using System.Text; using System.Xml; using System.Xml.Serialization; -using System.ComponentModel; -using System.Drawing; -using System.Diagnostics; +#if KeePassLibSD +using ICSharpCode.SharpZipLib.GZip; +#else +using System.IO.Compression; +#endif using KeePassLib.Interfaces; using KeePassLib.Utility; -#if !KeePassLibSD -using System.IO.Compression; -#else -using ICSharpCode.SharpZipLib.GZip; -#endif - namespace KeePassLib.Translation { [XmlRoot("Translation")] @@ -66,7 +62,7 @@ namespace KeePassLib.Translation m_vStringTables = value; } } - + /* private List m_vForms = new List(); [XmlArrayItem("Form")] @@ -80,7 +76,7 @@ namespace KeePassLib.Translation m_vForms = value; } } - + */ private string m_strUnusedText = string.Empty; [DefaultValue("")] public string UnusedText @@ -94,18 +90,25 @@ namespace KeePassLib.Translation } } - public static void SaveToFile(KPTranslation kpTrl, string strFileName, + public static void Save(KPTranslation kpTrl, string strFileName, + IXmlSerializerEx xs) + { + using(FileStream fs = new FileStream(strFileName, FileMode.Create, + FileAccess.Write, FileShare.None)) + { + Save(kpTrl, fs, xs); + } + } + + public static void Save(KPTranslation kpTrl, Stream sOut, IXmlSerializerEx xs) { if(xs == null) throw new ArgumentNullException("xs"); - FileStream fs = new FileStream(strFileName, FileMode.Create, - FileAccess.Write, FileShare.None); - #if !KeePassLibSD - GZipStream gz = new GZipStream(fs, CompressionMode.Compress); + GZipStream gz = new GZipStream(sOut, CompressionMode.Compress); #else - GZipOutputStream gz = new GZipOutputStream(fs); + GZipOutputStream gz = new GZipOutputStream(sOut); #endif XmlWriterSettings xws = new XmlWriterSettings(); @@ -120,27 +123,36 @@ namespace KeePassLib.Translation xw.Close(); gz.Close(); - fs.Close(); + sOut.Close(); } - public static KPTranslation LoadFromFile(string strFile, - IXmlSerializerEx xs) + public static KPTranslation Load(string strFile, IXmlSerializerEx xs) + { + KPTranslation kpTrl = null; + + using(FileStream fs = new FileStream(strFile, FileMode.Open, + FileAccess.Read, FileShare.Read)) + { + kpTrl = Load(fs, xs); + } + + return kpTrl; + } + + public static KPTranslation Load(Stream s, IXmlSerializerEx xs) { if(xs == null) throw new ArgumentNullException("xs"); - FileStream fs = new FileStream(strFile, FileMode.Open, - FileAccess.Read, FileShare.Read); - #if !KeePassLibSD - GZipStream gz = new GZipStream(fs, CompressionMode.Decompress); + GZipStream gz = new GZipStream(s, CompressionMode.Decompress); #else - GZipInputStream gz = new GZipInputStream(fs); + GZipInputStream gz = new GZipInputStream(s); #endif KPTranslation kpTrl = (xs.Deserialize(gz) as KPTranslation); gz.Close(); - fs.Close(); + s.Close(); return kpTrl; } @@ -154,9 +166,9 @@ namespace KeePassLib.Translation return new Dictionary(); } - -#if (!KeePassLibSD && !KeePassRT) - /*public void ApplyTo(Form form) + /* +#if (!KeePassLibSD && !KeePassUAP) + public void ApplyTo(Form form) { if(form == null) throw new ArgumentNullException("form"); @@ -185,8 +197,8 @@ namespace KeePassLib.Translation try { RtlApplyToControls(form.Controls); } catch(Exception) { Debug.Assert(false); } } - }*/ - /* + } + private static void RtlApplyToControls(Control.ControlCollection cc) { foreach(Control c in cc) @@ -212,9 +224,9 @@ namespace KeePassLib.Translation if((c is GroupBox) || (c is Panel)) RtlMoveChildControls(c); } - }*/ + } - /*private static void RtlMoveChildControls(Control cParent) + private static void RtlMoveChildControls(Control cParent) { int nParentWidth = cParent.Size.Width; @@ -248,7 +260,7 @@ namespace KeePassLib.Translation } if(kpst != null) kpst.ApplyTo(tsic); - }*/ -#endif + } +#endif*/ } } diff --git a/src/KeePassLib2Android/Translation/KPTranslationProperties.cs b/src/KeePassLib2Android/Translation/KPTranslationProperties.cs index 38515262..60b84db0 100644 --- a/src/KeePassLib2Android/Translation/KPTranslationProperties.cs +++ b/src/KeePassLib2Android/Translation/KPTranslationProperties.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/src/KeePassLib2Android/Utility/AppLogEx.cs b/src/KeePassLib2Android/Utility/AppLogEx.cs index ae16f699..53501856 100644 --- a/src/KeePassLib2Android/Utility/AppLogEx.cs +++ b/src/KeePassLib2Android/Utility/AppLogEx.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,9 +19,9 @@ using System; using System.Collections.Generic; -using System.Text; -using System.IO; using System.Diagnostics; +using System.IO; +using System.Text; #if !KeePassLibSD using System.IO.Compression; @@ -38,8 +38,7 @@ namespace KeePassLib.Utility public static void Open(string strPrefix) { - return; // Logging is not enabled in normal builds of KeePass! - + // Logging is not enabled in normal builds of KeePass! /* AppLogEx.Close(); diff --git a/src/KeePassLib2Android/Utility/MemUtil.cs b/src/KeePassLib2Android/Utility/MemUtil.cs index 8c2e937b..964e25a4 100644 --- a/src/KeePassLib2Android/Utility/MemUtil.cs +++ b/src/KeePassLib2Android/Utility/MemUtil.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,15 +19,15 @@ using System; using System.Collections.Generic; -using System.Text; -using System.Security.Cryptography; using System.Diagnostics; using System.IO; +using System.Runtime.CompilerServices; +using System.Text; -#if !KeePassLibSD -using System.IO.Compression; -#else +#if KeePassLibSD using KeePassLibSD; +#else +using System.IO.Compression; #endif namespace KeePassLib.Utility @@ -37,6 +37,8 @@ namespace KeePassLib.Utility /// public static class MemUtil { + internal static readonly byte[] EmptyByteArray = new byte[0]; + private static readonly uint[] m_vSBox = new uint[256] { 0xCD2FACB3, 0xE78A7F5C, 0x6F0803FC, 0xBCF6E230, 0x3A321712, 0x06403DB1, 0xD2F84B95, 0xDF22A6E4, @@ -187,75 +189,211 @@ namespace KeePassLib.Utility return sb.ToString(); } + /// + /// Decode Base32 strings according to RFC 4648. + /// + public static byte[] ParseBase32(string str) + { + if((str == null) || ((str.Length % 8) != 0)) + { + Debug.Assert(false); + return null; + } + + ulong uMaxBits = (ulong)str.Length * 5UL; + List l = new List((int)(uMaxBits / 8UL) + 1); + Debug.Assert(l.Count == 0); + + for(int i = 0; i < str.Length; i += 8) + { + ulong u = 0; + int nBits = 0; + + for(int j = 0; j < 8; ++j) + { + char ch = str[i + j]; + if(ch == '=') break; + + ulong uValue; + if((ch >= 'A') && (ch <= 'Z')) + uValue = (ulong)(ch - 'A'); + else if((ch >= 'a') && (ch <= 'z')) + uValue = (ulong)(ch - 'a'); + else if((ch >= '2') && (ch <= '7')) + uValue = (ulong)(ch - '2') + 26UL; + else { Debug.Assert(false); return null; } + + u <<= 5; + u += uValue; + nBits += 5; + } + + int nBitsTooMany = (nBits % 8); + u >>= nBitsTooMany; + nBits -= nBitsTooMany; + Debug.Assert((nBits % 8) == 0); + + int idxNewBytes = l.Count; + while(nBits > 0) + { + l.Add((byte)(u & 0xFF)); + u >>= 8; + nBits -= 8; + } + l.Reverse(idxNewBytes, l.Count - idxNewBytes); + } + + return l.ToArray(); + } + /// /// Set all bytes in a byte array to zero. /// - /// Input array. All bytes of this array will be set - /// to zero. + /// Input array. All bytes of this array + /// will be set to zero. +#if KeePassLibSD + [MethodImpl(MethodImplOptions.NoInlining)] +#else + [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] +#endif public static void ZeroByteArray(byte[] pbArray) { - Debug.Assert(pbArray != null); if(pbArray == null) throw new ArgumentNullException("pbArray"); - - // for(int i = 0; i < pbArray.Length; ++i) - // pbArray[i] = 0; + Debug.Assert(pbArray != null); + if(pbArray == null) throw new ArgumentNullException("pbArray"); Array.Clear(pbArray, 0, pbArray.Length); } /// - /// Convert 2 bytes to a 16-bit unsigned integer using Little-Endian - /// encoding. + /// Set all elements of an array to the default value. + /// + /// Input array. +#if KeePassLibSD + [MethodImpl(MethodImplOptions.NoInlining)] +#else + [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] +#endif + public static void ZeroArray(T[] v) + { + if(v == null) { Debug.Assert(false); throw new ArgumentNullException("v"); } + + Array.Clear(v, 0, v.Length); + } + + /// + /// Convert 2 bytes to a 16-bit unsigned integer (little-endian). /// - /// Input bytes. Array must contain at least 2 bytes. - /// 16-bit unsigned integer. public static ushort BytesToUInt16(byte[] pb) { Debug.Assert((pb != null) && (pb.Length == 2)); if(pb == null) throw new ArgumentNullException("pb"); - if(pb.Length != 2) throw new ArgumentException(); + if(pb.Length != 2) throw new ArgumentOutOfRangeException("pb"); return (ushort)((ushort)pb[0] | ((ushort)pb[1] << 8)); } /// - /// Convert 4 bytes to a 32-bit unsigned integer using Little-Endian - /// encoding. + /// Convert 2 bytes to a 16-bit unsigned integer (little-endian). + /// + public static ushort BytesToUInt16(byte[] pb, int iOffset) + { + if(pb == null) { Debug.Assert(false); throw new ArgumentNullException("pb"); } + if((iOffset < 0) || ((iOffset + 1) >= pb.Length)) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("iOffset"); + } + + return (ushort)((ushort)pb[iOffset] | ((ushort)pb[iOffset + 1] << 8)); + } + + /// + /// Convert 4 bytes to a 32-bit unsigned integer (little-endian). /// - /// Input bytes. - /// 32-bit unsigned integer. public static uint BytesToUInt32(byte[] pb) { Debug.Assert((pb != null) && (pb.Length == 4)); if(pb == null) throw new ArgumentNullException("pb"); - if(pb.Length != 4) throw new ArgumentException("Input array must contain 4 bytes!"); + if(pb.Length != 4) throw new ArgumentOutOfRangeException("pb"); - return (uint)pb[0] | ((uint)pb[1] << 8) | ((uint)pb[2] << 16) | - ((uint)pb[3] << 24); + return ((uint)pb[0] | ((uint)pb[1] << 8) | ((uint)pb[2] << 16) | + ((uint)pb[3] << 24)); } /// - /// Convert 8 bytes to a 64-bit unsigned integer using Little-Endian - /// encoding. + /// Convert 4 bytes to a 32-bit unsigned integer (little-endian). + /// + public static uint BytesToUInt32(byte[] pb, int iOffset) + { + if(pb == null) { Debug.Assert(false); throw new ArgumentNullException("pb"); } + if((iOffset < 0) || ((iOffset + 3) >= pb.Length)) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("iOffset"); + } + + return ((uint)pb[iOffset] | ((uint)pb[iOffset + 1] << 8) | + ((uint)pb[iOffset + 2] << 16) | ((uint)pb[iOffset + 3] << 24)); + } + + /// + /// Convert 8 bytes to a 64-bit unsigned integer (little-endian). /// - /// Input bytes. - /// 64-bit unsigned integer. public static ulong BytesToUInt64(byte[] pb) { Debug.Assert((pb != null) && (pb.Length == 8)); if(pb == null) throw new ArgumentNullException("pb"); - if(pb.Length != 8) throw new ArgumentException(); + if(pb.Length != 8) throw new ArgumentOutOfRangeException("pb"); - return (ulong)pb[0] | ((ulong)pb[1] << 8) | ((ulong)pb[2] << 16) | + return ((ulong)pb[0] | ((ulong)pb[1] << 8) | ((ulong)pb[2] << 16) | ((ulong)pb[3] << 24) | ((ulong)pb[4] << 32) | ((ulong)pb[5] << 40) | - ((ulong)pb[6] << 48) | ((ulong)pb[7] << 56); + ((ulong)pb[6] << 48) | ((ulong)pb[7] << 56)); } /// - /// Convert a 16-bit unsigned integer to 2 bytes using Little-Endian - /// encoding. + /// Convert 8 bytes to a 64-bit unsigned integer (little-endian). + /// + public static ulong BytesToUInt64(byte[] pb, int iOffset) + { + if(pb == null) { Debug.Assert(false); throw new ArgumentNullException("pb"); } + if((iOffset < 0) || ((iOffset + 7) >= pb.Length)) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("iOffset"); + } + + // if(BitConverter.IsLittleEndian) + // return BitConverter.ToUInt64(pb, iOffset); + + return ((ulong)pb[iOffset] | ((ulong)pb[iOffset + 1] << 8) | + ((ulong)pb[iOffset + 2] << 16) | ((ulong)pb[iOffset + 3] << 24) | + ((ulong)pb[iOffset + 4] << 32) | ((ulong)pb[iOffset + 5] << 40) | + ((ulong)pb[iOffset + 6] << 48) | ((ulong)pb[iOffset + 7] << 56)); + } + + public static int BytesToInt32(byte[] pb) + { + return (int)BytesToUInt32(pb); + } + + public static int BytesToInt32(byte[] pb, int iOffset) + { + return (int)BytesToUInt32(pb, iOffset); + } + + public static long BytesToInt64(byte[] pb) + { + return (long)BytesToUInt64(pb); + } + + public static long BytesToInt64(byte[] pb, int iOffset) + { + return (long)BytesToUInt64(pb, iOffset); + } + + /// + /// Convert a 16-bit unsigned integer to 2 bytes (little-endian). /// - /// 16-bit input word. - /// Two bytes representing the 16-bit value. public static byte[] UInt16ToBytes(ushort uValue) { byte[] pb = new byte[2]; @@ -270,11 +408,8 @@ namespace KeePassLib.Utility } /// - /// Convert a 32-bit unsigned integer to 4 bytes using Little-Endian - /// encoding. + /// Convert a 32-bit unsigned integer to 4 bytes (little-endian). /// - /// 32-bit input word. - /// Four bytes representing the 32-bit value. public static byte[] UInt32ToBytes(uint uValue) { byte[] pb = new byte[4]; @@ -291,11 +426,29 @@ namespace KeePassLib.Utility } /// - /// Convert a 64-bit unsigned integer to 8 bytes using Little-Endian - /// encoding. + /// Convert a 32-bit unsigned integer to 4 bytes (little-endian). + /// + public static void UInt32ToBytesEx(uint uValue, byte[] pb, int iOffset) + { + if(pb == null) { Debug.Assert(false); throw new ArgumentNullException("pb"); } + if((iOffset < 0) || ((iOffset + 3) >= pb.Length)) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("iOffset"); + } + + unchecked + { + pb[iOffset] = (byte)uValue; + pb[iOffset + 1] = (byte)(uValue >> 8); + pb[iOffset + 2] = (byte)(uValue >> 16); + pb[iOffset + 3] = (byte)(uValue >> 24); + } + } + + /// + /// Convert a 64-bit unsigned integer to 8 bytes (little-endian). /// - /// 64-bit input word. - /// Eight bytes representing the 64-bit value. public static byte[] UInt64ToBytes(ulong uValue) { byte[] pb = new byte[8]; @@ -315,6 +468,61 @@ namespace KeePassLib.Utility return pb; } + /// + /// Convert a 64-bit unsigned integer to 8 bytes (little-endian). + /// + public static void UInt64ToBytesEx(ulong uValue, byte[] pb, int iOffset) + { + if(pb == null) { Debug.Assert(false); throw new ArgumentNullException("pb"); } + if((iOffset < 0) || ((iOffset + 7) >= pb.Length)) + { + Debug.Assert(false); + throw new ArgumentOutOfRangeException("iOffset"); + } + + unchecked + { + pb[iOffset] = (byte)uValue; + pb[iOffset + 1] = (byte)(uValue >> 8); + pb[iOffset + 2] = (byte)(uValue >> 16); + pb[iOffset + 3] = (byte)(uValue >> 24); + pb[iOffset + 4] = (byte)(uValue >> 32); + pb[iOffset + 5] = (byte)(uValue >> 40); + pb[iOffset + 6] = (byte)(uValue >> 48); + pb[iOffset + 7] = (byte)(uValue >> 56); + } + } + + public static byte[] Int32ToBytes(int iValue) + { + return UInt32ToBytes((uint)iValue); + } + + public static byte[] Int64ToBytes(long lValue) + { + return UInt64ToBytes((ulong)lValue); + } + + public static uint RotateLeft32(uint u, int nBits) + { + return ((u << nBits) | (u >> (32 - nBits))); + } + + public static uint RotateRight32(uint u, int nBits) + { + return ((u >> nBits) | (u << (32 - nBits))); + } + + public static ulong RotateLeft64(ulong u, int nBits) + { + return ((u << nBits) | (u >> (64 - nBits))); + } + + public static ulong RotateRight64(ulong u, int nBits) + { + return ((u >> nBits) | (u << (64 - nBits))); + } + public static bool ArraysEqual(byte[] x, byte[] y) { // Return false if one of them is null (not comparable)! @@ -330,19 +538,21 @@ namespace KeePassLib.Utility return true; } - public static void XorArray(byte[] pbSource, int nSourceOffset, - byte[] pbBuffer, int nBufferOffset, int nLength) + public static void XorArray(byte[] pbSource, int iSourceOffset, + byte[] pbBuffer, int iBufferOffset, int cb) { if(pbSource == null) throw new ArgumentNullException("pbSource"); - if(nSourceOffset < 0) throw new ArgumentException(); + if(iSourceOffset < 0) throw new ArgumentOutOfRangeException("iSourceOffset"); if(pbBuffer == null) throw new ArgumentNullException("pbBuffer"); - if(nBufferOffset < 0) throw new ArgumentException(); - if(nLength < 0) throw new ArgumentException(); - if((nSourceOffset + nLength) > pbSource.Length) throw new ArgumentException(); - if((nBufferOffset + nLength) > pbBuffer.Length) throw new ArgumentException(); + if(iBufferOffset < 0) throw new ArgumentOutOfRangeException("iBufferOffset"); + if(cb < 0) throw new ArgumentOutOfRangeException("cb"); + if(iSourceOffset > (pbSource.Length - cb)) + throw new ArgumentOutOfRangeException("cb"); + if(iBufferOffset > (pbBuffer.Length - cb)) + throw new ArgumentOutOfRangeException("cb"); - for(int i = 0; i < nLength; ++i) - pbBuffer[nBufferOffset + i] ^= pbSource[nSourceOffset + i]; + for(int i = 0; i < cb; ++i) + pbBuffer[iBufferOffset + i] ^= pbSource[iSourceOffset + i]; } /// @@ -421,7 +631,8 @@ namespace KeePassLib.Utility if(s == null) { Debug.Assert(false); return; } if(pbData == null) { Debug.Assert(false); return; } - s.Write(pbData, 0, pbData.Length); + Debug.Assert(pbData.Length >= 0); + if(pbData.Length > 0) s.Write(pbData, 0, pbData.Length); } public static byte[] Compress(byte[] pbData) @@ -429,15 +640,21 @@ namespace KeePassLib.Utility if(pbData == null) throw new ArgumentNullException("pbData"); if(pbData.Length == 0) return pbData; - MemoryStream msCompressed = new MemoryStream(); - GZipStream gz = new GZipStream(msCompressed, CompressionMode.Compress); - MemoryStream msSource = new MemoryStream(pbData, false); - MemUtil.CopyStream(msSource, gz); - gz.Close(); - msSource.Close(); + byte[] pbCompressed; + using(MemoryStream msSource = new MemoryStream(pbData, false)) + { + using(MemoryStream msCompressed = new MemoryStream()) + { + using(GZipStream gz = new GZipStream(msCompressed, + CompressionMode.Compress)) + { + MemUtil.CopyStream(msSource, gz); + } + + pbCompressed = msCompressed.ToArray(); + } + } - byte[] pbCompressed = msCompressed.ToArray(); - msCompressed.Close(); return pbCompressed; } @@ -446,15 +663,21 @@ namespace KeePassLib.Utility if(pbCompressed == null) throw new ArgumentNullException("pbCompressed"); if(pbCompressed.Length == 0) return pbCompressed; - MemoryStream msCompressed = new MemoryStream(pbCompressed, false); - GZipStream gz = new GZipStream(msCompressed, CompressionMode.Decompress); - MemoryStream msData = new MemoryStream(); - MemUtil.CopyStream(gz, msData); - gz.Close(); - msCompressed.Close(); + byte[] pbData; + using(MemoryStream msData = new MemoryStream()) + { + using(MemoryStream msCompressed = new MemoryStream(pbCompressed, false)) + { + using(GZipStream gz = new GZipStream(msCompressed, + CompressionMode.Decompress)) + { + MemUtil.CopyStream(gz, msData); + } + } + + pbData = msData.ToArray(); + } - byte[] pbData = msData.ToArray(); - msData.Close(); return pbData; } diff --git a/src/KeePassLib2Android/Utility/MonoWorkarounds.cs b/src/KeePassLib2Android/Utility/MonoWorkarounds.cs new file mode 100644 index 00000000..76410a51 --- /dev/null +++ b/src/KeePassLib2Android/Utility/MonoWorkarounds.cs @@ -0,0 +1,183 @@ +/* + KeePass Password Safe - The Open-Source Password Manager + Copyright (C) 2003-2016 Dominik Reichl + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Text; +using System.Xml; + + +using KeePassLib.Native; + +namespace KeePassLib.Utility +{ + public static class MonoWorkarounds + { + private static Dictionary m_dForceReq = new Dictionary(); + + private static bool? m_bReq = null; + public static bool IsRequired() + { + if(!m_bReq.HasValue) m_bReq = NativeLib.IsUnix(); + return m_bReq.Value; + } + + // 1219: + // Mono prepends byte order mark (BOM) to StdIn. + // https://sourceforge.net/p/keepass/bugs/1219/ + // 1245: + // Key events not raised while Alt is down, and nav keys out of order. + // https://sourceforge.net/p/keepass/bugs/1245/ + // 1254: + // NumericUpDown bug: text is drawn below up/down buttons. + // https://sourceforge.net/p/keepass/bugs/1254/ + // 1354: + // Finalizer of NotifyIcon throws on Unity. + // https://sourceforge.net/p/keepass/bugs/1354/ + // 1358: + // FileDialog crashes when ~/.recently-used is invalid. + // https://sourceforge.net/p/keepass/bugs/1358/ + // 1366: + // Drawing bug when scrolling a RichTextBox. + // https://sourceforge.net/p/keepass/bugs/1366/ + // 1378: + // Mono doesn't implement Microsoft.Win32.SystemEvents events. + // https://sourceforge.net/p/keepass/bugs/1378/ + // https://github.com/mono/mono/blob/master/mcs/class/System/Microsoft.Win32/SystemEvents.cs + // 1418: + // Minimizing a form while loading it doesn't work. + // https://sourceforge.net/p/keepass/bugs/1418/ + // 2139: + // Shortcut keys are ignored. + // https://sourceforge.net/p/keepass/feature-requests/2139/ + // 2140: + // Explicit control focusing is ignored. + // https://sourceforge.net/p/keepass/feature-requests/2140/ + // 5795: + // Text in input field is incomplete. + // https://bugzilla.xamarin.com/show_bug.cgi?id=5795 + // https://sourceforge.net/p/keepass/discussion/329220/thread/d23dc88b/ + // 10163: + // WebRequest GetResponse call missing, breaks WebDAV due to no PUT. + // https://bugzilla.xamarin.com/show_bug.cgi?id=10163 + // https://sourceforge.net/p/keepass/bugs/1117/ + // https://sourceforge.net/p/keepass/discussion/329221/thread/9422258c/ + // https://github.com/mono/mono/commit/8e67b8c2fc7cb66bff7816ebf7c1039fb8cfc43b + // https://bugzilla.xamarin.com/show_bug.cgi?id=1512 + // https://sourceforge.net/p/keepass/patches/89/ + // 12525: + // PictureBox not rendered when bitmap height >= control height. + // https://bugzilla.xamarin.com/show_bug.cgi?id=12525 + // https://sourceforge.net/p/keepass/discussion/329220/thread/54f61e9a/ + // 586901: + // RichTextBox doesn't handle Unicode string correctly. + // https://bugzilla.novell.com/show_bug.cgi?id=586901 + // 620618: + // ListView column headers not drawn. + // https://bugzilla.novell.com/show_bug.cgi?id=620618 + // 649266: + // Calling Control.Hide doesn't remove the application from taskbar. + // https://bugzilla.novell.com/show_bug.cgi?id=649266 + // 686017: + // Minimum sizes must be enforced. + // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=686017 + // 801414: + // Mono recreates the main window incorrectly. + // https://bugs.launchpad.net/ubuntu/+source/keepass2/+bug/801414 + // 891029: + // Increase tab control height, otherwise Mono throws exceptions. + // https://sourceforge.net/projects/keepass/forums/forum/329221/topic/4519750 + // https://bugs.launchpad.net/ubuntu/+source/keepass2/+bug/891029 + // 836428016: + // ListView group header selection unsupported. + // https://sourceforge.net/p/keepass/discussion/329221/thread/31dae0f0/ + // 3574233558: + // Problems with minimizing windows, no content rendered. + // https://sourceforge.net/p/keepass/discussion/329220/thread/d50a79d6/ + public static bool IsRequired(uint uBugID) + { + if(!MonoWorkarounds.IsRequired()) return false; + + bool bForce; + if(m_dForceReq.TryGetValue(uBugID, out bForce)) return bForce; + + ulong v = NativeLib.MonoVersion; + if(v != 0) + { + if(uBugID == 10163) + return (v >= 0x0002000B00000000UL); // >= 2.11 + } + + return true; + } + + internal static void SetEnabled(string strIDs, bool bEnabled) + { + if(string.IsNullOrEmpty(strIDs)) return; + + string[] vIDs = strIDs.Split(new char[] { ',' }); + foreach(string strID in vIDs) + { + if(string.IsNullOrEmpty(strID)) continue; + + uint uID; + if(StrUtil.TryParseUInt(strID.Trim(), out uID)) + m_dForceReq[uID] = bEnabled; + } + } + + /// + /// Ensure that the file ~/.recently-used is valid (in order to + /// prevent Mono's FileDialog from crashing). + /// + internal static void EnsureRecentlyUsedValid() + { + if(!MonoWorkarounds.IsRequired(1358)) return; + + try + { + string strFile = Environment.GetFolderPath( + Environment.SpecialFolder.Personal); + strFile = UrlUtil.EnsureTerminatingSeparator(strFile, false); + strFile += ".recently-used"; + + if(File.Exists(strFile)) + { + try + { + // Mono's WriteRecentlyUsedFiles method also loads the + // XML file using XmlDocument + XmlDocument xd = new XmlDocument(); + xd.Load(strFile); + } + catch(Exception) // The XML file is invalid + { + File.Delete(strFile); + } + } + } + catch(Exception) { Debug.Assert(false); } + } + + } +} diff --git a/src/KeePassLib2Android/Utility/StrUtil.cs b/src/KeePassLib2Android/Utility/StrUtil.cs index 3e742984..8625eaf4 100644 --- a/src/KeePassLib2Android/Utility/StrUtil.cs +++ b/src/KeePassLib2Android/Utility/StrUtil.cs @@ -1,8 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl - - Modified to be used with Mono for Android. Changes Copyright (C) 2013 Philipp Crocoll + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -22,19 +20,21 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.IO; -using System.Text.RegularExpressions; -using System.Security.Cryptography; -using System.Globalization; using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; + +#if !KeePassUAP +using System.Drawing; +using System.Security.Cryptography; +#endif using KeePassLib.Collections; using KeePassLib.Cryptography.PasswordGenerator; using KeePassLib.Native; using KeePassLib.Security; -using KeePassLib.Resources; namespace KeePassLib.Utility { @@ -221,8 +221,8 @@ namespace KeePassLib.Utility List l = new List(); l.Add(new StrEncodingInfo(StrEncodingType.Default, -#if KeePassRT - StrUtil.Utf8.WebName, StrUtil.Utf8, 1, null)); +#if KeePassUAP + "Unicode (UTF-8)", StrUtil.Utf8, 1, new byte[] { 0xEF, 0xBB, 0xBF })); #else #if !KeePassLibSD Encoding.Default.EncodingName, @@ -232,12 +232,11 @@ namespace KeePassLib.Utility Encoding.Default, (uint)Encoding.Default.GetBytes("a").Length, null)); #endif -#if !KeePassRT + l.Add(new StrEncodingInfo(StrEncodingType.Ascii, "ASCII", Encoding.ASCII, 1, null)); l.Add(new StrEncodingInfo(StrEncodingType.Utf7, "Unicode (UTF-7)", Encoding.UTF7, 1, null)); -#endif l.Add(new StrEncodingInfo(StrEncodingType.Utf8, "Unicode (UTF-8)", StrUtil.Utf8, 1, new byte[] { 0xEF, 0xBB, 0xBF })); l.Add(new StrEncodingInfo(StrEncodingType.Utf16LE, @@ -246,7 +245,8 @@ namespace KeePassLib.Utility l.Add(new StrEncodingInfo(StrEncodingType.Utf16BE, "Unicode (UTF-16 BE)", new UnicodeEncoding(true, false), 2, new byte[] { 0xFE, 0xFF })); -#if (!KeePassLibSD && !KeePassRT) + +#if !KeePassLibSD l.Add(new StrEncodingInfo(StrEncodingType.Utf32LE, "Unicode (UTF-32 LE)", new UTF32Encoding(false, false), 4, new byte[] { 0xFF, 0xFE, 0x0, 0x0 })); @@ -315,7 +315,7 @@ namespace KeePassLib.Utility str = str.Replace("\'", @"'"); str = NormalizeNewLines(str, false); - str = str.Replace("\n", @"
"); + str = str.Replace("\n", @"
\n" ); return str; } @@ -358,9 +358,9 @@ namespace KeePassLib.Utility } /// - /// Split up a command-line into application and argument. + /// Split up a command line into application and argument. /// - /// Command-line to split. + /// Command line to split. /// Application path. /// Arguments. public static void SplitCommandLine(string strCmdLine, out string strApp, out string strArgs) @@ -487,53 +487,53 @@ namespace KeePassLib.Utility public static string FormatException(Exception excp) { string strText = string.Empty; - + string NewLine = "\n"; if(excp.Message != null) - strText += excp.Message + MessageService.NewLine; + strText += excp.Message + NewLine; #if !KeePassLibSD if(excp.Source != null) - strText += excp.Source + MessageService.NewLine; + strText += excp.Source + NewLine; #endif if(excp.StackTrace != null) - strText += excp.StackTrace + MessageService.NewLine; + strText += excp.StackTrace + NewLine; #if !KeePassLibSD -#if !KeePassRT +#if !KeePassUAP if(excp.TargetSite != null) - strText += excp.TargetSite.ToString() + MessageService.NewLine; + strText += excp.TargetSite.ToString() + NewLine; #endif if(excp.Data != null) { - strText += MessageService.NewLine; + strText += NewLine; foreach(DictionaryEntry de in excp.Data) strText += @"'" + de.Key + @"' -> '" + de.Value + @"'" + - MessageService.NewLine; + NewLine; } #endif if(excp.InnerException != null) { - strText += MessageService.NewLine + "Inner:" + MessageService.NewLine; + strText += NewLine + "Inner:" + NewLine; if(excp.InnerException.Message != null) - strText += excp.InnerException.Message + MessageService.NewLine; + strText += excp.InnerException.Message + NewLine; #if !KeePassLibSD if(excp.InnerException.Source != null) - strText += excp.InnerException.Source + MessageService.NewLine; + strText += excp.InnerException.Source + NewLine; #endif if(excp.InnerException.StackTrace != null) - strText += excp.InnerException.StackTrace + MessageService.NewLine; + strText += excp.InnerException.StackTrace + NewLine; #if !KeePassLibSD -#if !KeePassRT +#if !KeePassUAP if(excp.InnerException.TargetSite != null) strText += excp.InnerException.TargetSite.ToString(); #endif if(excp.InnerException.Data != null) { - strText += MessageService.NewLine; + strText += NewLine; foreach(DictionaryEntry de in excp.InnerException.Data) strText += @"'" + de.Key + @"' -> '" + de.Value + @"'" + - MessageService.NewLine; + NewLine; } #endif } @@ -760,7 +760,7 @@ namespace KeePassLib.Utility return sb.ToString(); } - private static Regex m_rxNaturalSplit = null; + /* private static Regex g_rxNaturalSplit = null; public static int CompareNaturally(string strX, string strY) { Debug.Assert(strX != null); @@ -771,39 +771,31 @@ namespace KeePassLib.Utility if(NativeMethods.SupportsStrCmpNaturally) return NativeMethods.StrCmpNaturally(strX, strY); - strX = strX.ToLower(); // Case-insensitive comparison - strY = strY.ToLower(); + if(g_rxNaturalSplit == null) + g_rxNaturalSplit = new Regex(@"([0-9]+)", RegexOptions.Compiled); - if(m_rxNaturalSplit == null) - m_rxNaturalSplit = new Regex(@"([0-9]+)", -#if KeePassRT - RegexOptions.None); -#else - RegexOptions.Compiled); -#endif + string[] vPartsX = g_rxNaturalSplit.Split(strX); + string[] vPartsY = g_rxNaturalSplit.Split(strY); - string[] vPartsX = m_rxNaturalSplit.Split(strX); - string[] vPartsY = m_rxNaturalSplit.Split(strY); - - for(int i = 0; i < Math.Min(vPartsX.Length, vPartsY.Length); ++i) + int n = Math.Min(vPartsX.Length, vPartsY.Length); + for(int i = 0; i < n; ++i) { string strPartX = vPartsX[i], strPartY = vPartsY[i]; int iPartCompare; #if KeePassLibSD - ulong uX = 0, uY = 0; try { - uX = ulong.Parse(strPartX); - uY = ulong.Parse(strPartY); + ulong uX = ulong.Parse(strPartX); + ulong uY = ulong.Parse(strPartY); iPartCompare = uX.CompareTo(uY); } - catch(Exception) { iPartCompare = strPartX.CompareTo(strPartY); } + catch(Exception) { iPartCompare = string.Compare(strPartX, strPartY, true); } #else ulong uX, uY; if(ulong.TryParse(strPartX, out uX) && ulong.TryParse(strPartY, out uY)) iPartCompare = uX.CompareTo(uY); - else iPartCompare = strPartX.CompareTo(strPartY); + else iPartCompare = string.Compare(strPartX, strPartY, true); #endif if(iPartCompare != 0) return iPartCompare; @@ -812,6 +804,106 @@ namespace KeePassLib.Utility if(vPartsX.Length == vPartsY.Length) return 0; if(vPartsX.Length < vPartsY.Length) return -1; return 1; + } */ + + public static int CompareNaturally(string strX, string strY) + { + Debug.Assert(strX != null); + if(strX == null) throw new ArgumentNullException("strX"); + Debug.Assert(strY != null); + if(strY == null) throw new ArgumentNullException("strY"); + + if(NativeMethods.SupportsStrCmpNaturally) + return NativeMethods.StrCmpNaturally(strX, strY); + + int cX = strX.Length; + int cY = strY.Length; + if(cX == 0) return ((cY == 0) ? 0 : -1); + if(cY == 0) return 1; + + char chFirstX = strX[0]; + char chFirstY = strY[0]; + bool bExpNum = ((chFirstX >= '0') && (chFirstX <= '9')); + bool bExpNumY = ((chFirstY >= '0') && (chFirstY <= '9')); + if(bExpNum != bExpNumY) return string.Compare(strX, strY, true); + + int pX = 0; + int pY = 0; + while((pX < cX) && (pY < cY)) + { + Debug.Assert(((strX[pX] >= '0') && (strX[pX] <= '9')) == bExpNum); + Debug.Assert(((strY[pY] >= '0') && (strY[pY] <= '9')) == bExpNum); + + int pExclX = pX + 1; + while(pExclX < cX) + { + char ch = strX[pExclX]; + bool bChNum = ((ch >= '0') && (ch <= '9')); + if(bChNum != bExpNum) break; + ++pExclX; + } + + int pExclY = pY + 1; + while(pExclY < cY) + { + char ch = strY[pExclY]; + bool bChNum = ((ch >= '0') && (ch <= '9')); + if(bChNum != bExpNum) break; + ++pExclY; + } + + string strPartX = strX.Substring(pX, pExclX - pX); + string strPartY = strY.Substring(pY, pExclY - pY); + + bool bStrCmp = true; + if(bExpNum) + { + // 2^64 - 1 = 18446744073709551615 has length 20 + if((strPartX.Length <= 19) && (strPartY.Length <= 19)) + { + ulong uX, uY; + if(ulong.TryParse(strPartX, out uX) && ulong.TryParse(strPartY, out uY)) + { + if(uX < uY) return -1; + if(uX > uY) return 1; + + bStrCmp = false; + } + else { Debug.Assert(false); } + } + else + { + double dX, dY; + if(double.TryParse(strPartX, out dX) && double.TryParse(strPartY, out dY)) + { + if(dX < dY) return -1; + if(dX > dY) return 1; + + bStrCmp = false; + } + else { Debug.Assert(false); } + } + } + if(bStrCmp) + { + int c = string.Compare(strPartX, strPartY, true); + if(c != 0) return c; + } + + bExpNum = !bExpNum; + pX = pExclX; + pY = pExclY; + } + + if(pX >= cX) + { + Debug.Assert(pX == cX); + if(pY >= cY) { Debug.Assert(pY == cY); return 0; } + return -1; + } + + Debug.Assert(pY == cY); + return 1; } public static string RemoveAccelerator(string strMenuText) @@ -835,6 +927,40 @@ namespace KeePassLib.Utility return str; } + public static string AddAccelerator(string strMenuText, + List lAvailKeys) + { + if(strMenuText == null) { Debug.Assert(false); return null; } + if(lAvailKeys == null) { Debug.Assert(false); return strMenuText; } + + int xa = -1, xs = 0; + for(int i = 0; i < strMenuText.Length; ++i) + { + char ch = strMenuText[i]; + +#if KeePassLibSD + char chUpper = char.ToUpper(ch); +#else + char chUpper = char.ToUpperInvariant(ch); +#endif + xa = lAvailKeys.IndexOf(chUpper); + if(xa >= 0) { xs = i; break; } + +#if KeePassLibSD + char chLower = char.ToLower(ch); +#else + char chLower = char.ToLowerInvariant(ch); +#endif + xa = lAvailKeys.IndexOf(chLower); + if(xa >= 0) { xs = i; break; } + } + + if(xa < 0) return strMenuText; + + lAvailKeys.RemoveAt(xa); + return strMenuText.Insert(xs, @"&"); + } + public static string EncodeMenuText(string strText) { if(strText == null) throw new ArgumentNullException("strText"); @@ -852,13 +978,12 @@ namespace KeePassLib.Utility public static bool IsHexString(string str, bool bStrict) { if(str == null) throw new ArgumentNullException("str"); - if(str.Length == 0) return true; foreach(char ch in str) { if((ch >= '0') && (ch <= '9')) continue; - if((ch >= 'a') && (ch <= 'z')) continue; - if((ch >= 'A') && (ch <= 'Z')) continue; + if((ch >= 'a') && (ch <= 'f')) continue; + if((ch >= 'A') && (ch <= 'F')) continue; if(bStrict) return false; @@ -871,8 +996,31 @@ namespace KeePassLib.Utility return true; } + public static bool IsHexString(byte[] pbUtf8, bool bStrict) + { + if(pbUtf8 == null) throw new ArgumentNullException("pbUtf8"); + + for(int i = 0; i < pbUtf8.Length; ++i) + { + byte bt = pbUtf8[i]; + if((bt >= (byte)'0') && (bt <= (byte)'9')) continue; + if((bt >= (byte)'a') && (bt <= (byte)'f')) continue; + if((bt >= (byte)'A') && (bt <= (byte)'F')) continue; + + if(bStrict) return false; + + if((bt == (byte)' ') || (bt == (byte)'\t') || + (bt == (byte)'\r') || (bt == (byte)'\n')) + continue; + + return false; + } + + return true; + } + #if !KeePassLibSD - private static readonly char[] m_vPatternPartsSep = new char[]{ '*' }; + private static readonly char[] m_vPatternPartsSep = new char[] { '*' }; public static bool SimplePatternMatch(string strPattern, string strText, StringComparison sc) { @@ -997,6 +1145,36 @@ namespace KeePassLib.Utility } } + public static string GetNewLineSeq(string str) + { + if(str == null) { Debug.Assert(false); return "\n"; } + + int n = str.Length, nLf = 0, nCr = 0, nCrLf = 0; + char chLast = char.MinValue; + for(int i = 0; i < n; ++i) + { + char ch = str[i]; + + if(ch == '\r') ++nCr; + else if(ch == '\n') + { + ++nLf; + if(chLast == '\r') ++nCrLf; + } + + chLast = ch; + } + + nCr -= nCrLf; + nLf -= nCrLf; + + int nMax = Math.Max(nCrLf, Math.Max(nCr, nLf)); + if(nMax == 0) return "\n"; + + if(nCrLf == nMax) return "\r\n"; + return ((nLf == nMax) ? "\n" : "\r"); + } + public static string AlphaNumericOnly(string str) { if(string.IsNullOrEmpty(str)) return str; @@ -1074,37 +1252,44 @@ namespace KeePassLib.Utility public static string VersionToString(ulong uVersion) { - return VersionToString(uVersion, false); + return VersionToString(uVersion, 1U); } + [Obsolete] public static string VersionToString(ulong uVersion, bool bEnsureAtLeastTwoComp) { - string str = string.Empty; - bool bMultiComp = false; + return VersionToString(uVersion, (bEnsureAtLeastTwoComp ? 2U : 1U)); + } + + public static string VersionToString(ulong uVersion, uint uMinComp) + { + StringBuilder sb = new StringBuilder(); + uint uComp = 0; for(int i = 0; i < 4; ++i) { - ushort us = (ushort)(uVersion & 0xFFFFUL); + if(uVersion == 0UL) break; - if((us != 0) || (str.Length > 0)) - { - if(str.Length > 0) - { - str = "." + str; - bMultiComp = true; - } + ushort us = (ushort)(uVersion >> 48); - str = us.ToString(NumberFormatInfo.InvariantInfo) + str; - } + if(sb.Length > 0) sb.Append('.'); - uVersion >>= 16; + sb.Append(us.ToString(NumberFormatInfo.InvariantInfo)); + ++uComp; + + uVersion <<= 16; } - if(bEnsureAtLeastTwoComp && !bMultiComp && (str.Length > 0)) - str += ".0"; + while(uComp < uMinComp) + { + if(sb.Length > 0) sb.Append('.'); - return str; + sb.Append('0'); + ++uComp; + } + + return sb.ToString(); } private static readonly byte[] m_pbOptEnt = { 0xA5, 0x74, 0x2E, 0xEC }; @@ -1169,7 +1354,7 @@ namespace KeePassLib.Utility return v; } - private static readonly char[] m_vTagSep = new char[]{ ',', ';', ':' }; + private static readonly char[] m_vTagSep = new char[] { ',', ';', ':' }; public static string TagsToString(List vTags, bool bForDisplay) { if(vTags == null) throw new ArgumentNullException("vTags"); @@ -1222,7 +1407,7 @@ namespace KeePassLib.Utility Array.Reverse(pb); for(int i = 0; i < pb.Length; ++i) pb[i] = (byte)(pb[i] ^ 0x65); -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) return Convert.ToBase64String(pb, Base64FormattingOptions.None); #else return Convert.ToBase64String(pb); @@ -1382,7 +1567,7 @@ namespace KeePassLib.Utility if(strMimeType == null) strMimeType = "application/octet-stream"; -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) return ("data:" + strMimeType + ";base64," + Convert.ToBase64String( pbData, Base64FormattingOptions.None)); #else @@ -1412,12 +1597,7 @@ namespace KeePassLib.Utility if(bBase64) return Convert.FromBase64String(strData); MemoryStream ms = new MemoryStream(); - -#if KeePassRT - Encoding enc = StrUtil.Utf8; -#else Encoding enc = Encoding.ASCII; -#endif string[] v = strData.Split('%'); byte[] pb = enc.GetBytes(v[0]); diff --git a/src/KeePassLib2Android/Utility/TimeUtil.cs b/src/KeePassLib2Android/Utility/TimeUtil.cs index 360cf47b..2e67dfff 100644 --- a/src/KeePassLib2Android/Utility/TimeUtil.cs +++ b/src/KeePassLib2Android/Utility/TimeUtil.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,7 +18,10 @@ */ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; +using System.Text; using KeePassLib.Interfaces; @@ -35,9 +38,29 @@ namespace KeePassLib.Utility ///
public const int PwTimeLength = 7; +#if !KeePassLibSD + private static string m_strDtfStd = null; + private static string m_strDtfDate = null; +#endif /// + private static DateTime? m_odtUnixRoot = null; + public static DateTime UnixRoot + { + get + { + if(m_odtUnixRoot.HasValue) return m_odtUnixRoot.Value; /// Pack a DateTime object into 5 bytes. Layout: 2 zero bits, + DateTime dtRoot = (new DateTime(1970, 1, 1, 0, 0, 0, 0, + DateTimeKind.Utc)).ToLocalTime(); /// year 12 bits, month 4 bits, day 5 bits, hour 5 bits, minute 6 + m_odtUnixRoot = dtRoot; + return dtRoot; + } + } + /// bits, second 6 bits. + /// + /// + /// /// bits, second 6 bits. ///
/// @@ -140,17 +163,118 @@ namespace KeePassLib.Utility { DateTime dt; -#if !KeePassLibSD - if(DateTime.TryParse(strDisplay, out dt)) return dt; -#else +#if KeePassLibSD try { dt = DateTime.Parse(strDisplay); return dt; } catch(Exception) { } +#else + if(DateTime.TryParse(strDisplay, out dt)) return dt; + + // For some custom formats specified using the Control Panel, + // DateTime.ToString returns the correct string, but + // DateTime.TryParse fails (e.g. for "//dd/MMM/yyyy"); + // https://sourceforge.net/p/keepass/discussion/329221/thread/3a225b29/?limit=25&page=1#c6ae + if((m_strDtfStd == null) || (m_strDtfDate == null)) + { + DateTime dtUni = new DateTime(2111, 3, 4, 5, 6, 7); + m_strDtfStd = DeriveCustomFormat(ToDisplayString(dtUni), dtUni); + m_strDtfDate = DeriveCustomFormat(ToDisplayStringDateOnly(dtUni), dtUni); + } + const DateTimeStyles dts = DateTimeStyles.AllowWhiteSpaces; + if(DateTime.TryParseExact(strDisplay, m_strDtfStd, null, dts, out dt)) + return dt; + if(DateTime.TryParseExact(strDisplay, m_strDtfDate, null, dts, out dt)) + return dt; #endif Debug.Assert(false); return DateTime.Now; } +#if !KeePassLibSD + private static string DeriveCustomFormat(string strDT, DateTime dt) + { + string[] vPlh = new string[] { + // Names, sorted by length + "MMMM", "dddd", + "MMM", "ddd", + "gg", "g", + + // Numbers, the ones with prefix '0' first + "yyyy", "yyy", "yy", "y", + "MM", "M", + "dd", "d", + "HH", "hh", "H", "h", + "mm", "m", + "ss", "s", + + "tt", "t" + }; + + List lValues = new List(); + foreach(string strPlh in vPlh) + { + string strEval = strPlh; + if(strEval.Length == 1) strEval = @"%" + strPlh; // Make custom + + lValues.Add(dt.ToString(strEval)); + } + + StringBuilder sbAll = new StringBuilder(); + sbAll.Append("dfFghHKmMstyz:/\"\'\\%"); + sbAll.Append(strDT); + foreach(string strVEnum in lValues) { sbAll.Append(strVEnum); } + + List lCodes = new List(); + for(int i = 0; i < vPlh.Length; ++i) + { + char ch = StrUtil.GetUnusedChar(sbAll.ToString()); + lCodes.Add(ch); + sbAll.Append(ch); + } + + string str = strDT; + for(int i = 0; i < vPlh.Length; ++i) + { + string strValue = lValues[i]; + if(string.IsNullOrEmpty(strValue)) continue; + + str = str.Replace(strValue, new string(lCodes[i], 1)); + } + + StringBuilder sbFmt = new StringBuilder(); + bool bInLiteral = false; + foreach(char ch in str) + { + int iCode = lCodes.IndexOf(ch); + + // The escape character doesn't work correctly (e.g. + // "dd\\.MM\\.yyyy\\ HH\\:mm\\:ss" doesn't work, but + // "dd'.'MM'.'yyyy' 'HH':'mm':'ss" does); use '' instead + + // if(iCode >= 0) sbFmt.Append(vPlh[iCode]); + // else // Literal + // { + // sbFmt.Append('\\'); + // sbFmt.Append(ch); + // } + + if(iCode >= 0) + { + if(bInLiteral) { sbFmt.Append('\''); bInLiteral = false; } + sbFmt.Append(vPlh[iCode]); + } + else // Literal + { + if(!bInLiteral) { sbFmt.Append('\''); bInLiteral = true; } + sbFmt.Append(ch); + } + } + if(bInLiteral) sbFmt.Append('\''); + + return sbFmt.ToString(); + } +#endif + public static string SerializeUtc(DateTime dt) { string str = dt.ToUniversalTime().ToString("s"); diff --git a/src/KeePassLib2Android/Utility/UrlUtil.cs b/src/KeePassLib2Android/Utility/UrlUtil.cs index 50150134..ff0c349c 100644 --- a/src/KeePassLib2Android/Utility/UrlUtil.cs +++ b/src/KeePassLib2Android/Utility/UrlUtil.cs @@ -1,6 +1,6 @@ /* KeePass Password Safe - The Open-Source Password Manager - Copyright (C) 2003-2013 Dominik Reichl + Copyright (C) 2003-2016 Dominik Reichl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,10 +19,9 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; using System.Diagnostics; +using System.IO; +using System.Text; using KeePassLib.Native; @@ -41,17 +40,14 @@ namespace KeePassLib.Utility public static char LocalDirSepChar { -#if KeePassRT - get { return '\\'; } -#else get { return Path.DirectorySeparatorChar; } -#endif } /// - /// Get the directory (path) of a file name. The returned string is + /// Get the directory (path) of a file name. The returned string may be /// terminated by a directory separator character. Example: /// passing C:\\My Documents\\My File.kdb in + /// and true to /// would produce this string: C:\\My Documents\\. /// /// Full path of a file. @@ -62,8 +58,7 @@ namespace KeePassLib.Utility /// of X:, overriding ). /// This should only be set to true, if the returned path is directly /// passed to some directory API. - /// Directory of the file. The return value is an empty string - /// ("") if the input parameter is null. + /// Directory of the file. public static string GetFileDirectory(string strFile, bool bAppendTerminatingChar, bool bEnsureValidDirSpec) { @@ -71,14 +66,15 @@ namespace KeePassLib.Utility if(strFile == null) throw new ArgumentNullException("strFile"); int nLastSep = strFile.LastIndexOfAny(m_vDirSeps); - if(nLastSep < 0) return strFile; // None + if(nLastSep < 0) return string.Empty; // No directory if(bEnsureValidDirSpec && (nLastSep == 2) && (strFile[1] == ':') && (strFile[2] == '\\')) // Length >= 3 and Windows root directory bAppendTerminatingChar = true; if(!bAppendTerminatingChar) return strFile.Substring(0, nLastSep); - return EnsureTerminatingSeparator(strFile.Substring(0, nLastSep), false); + return EnsureTerminatingSeparator(strFile.Substring(0, nLastSep), + (strFile[nLastSep] == '/')); } /// @@ -317,10 +313,11 @@ namespace KeePassLib.Utility return strTargetFile; } -#if (!KeePassLibSD && !KeePassRT) +#if (!KeePassLibSD && !KeePassUAP) if(NativeLib.IsUnix()) #endif { + bool bBaseUnc = IsUncPath(strBaseFile); bool bTargetUnc = IsUncPath(strTargetFile); if((!bBaseUnc && bTargetUnc) || (bBaseUnc && !bTargetUnc)) @@ -348,9 +345,9 @@ namespace KeePassLib.Utility } return sbRel.ToString(); +#if (!KeePassLibSD && !KeePassUAP) } -#if (!KeePassLibSD && !KeePassRT) try // Windows { const int nMaxPath = NativeMethods.MAX_PATH * 2; @@ -624,7 +621,7 @@ namespace KeePassLib.Utility string strDir; if(NativeLib.IsUnix()) strDir = NativeMethods.GetUserRuntimeDir(); -#if KeePassRT +#if KeePassUAP else strDir = Windows.Storage.ApplicationData.Current.TemporaryFolder.Path; #else else strDir = Path.GetTempPath(); @@ -632,8 +629,7 @@ namespace KeePassLib.Utility try { - if(Directory.Exists(strDir) == false) - Directory.CreateDirectory(strDir); + if(!Directory.Exists(strDir)) Directory.CreateDirectory(strDir); } catch(Exception) { Debug.Assert(false); }